【问题标题】:not able to redirect the output to a file in ipython ide无法将输出重定向到 ipython ide 中的文件
【发布时间】:2017-09-04 13:36:30
【问题描述】:

我无法将 dir(modulename) 的输出重定向到 ipython ide 中的文件。请让我知道该怎么做。它适用于 ls 和其他 linux 命令。

 In [45]: os.system('dir(socket) > socket1.txt')
 File Not Found
 Out[45]: 1

 In [46]: os.system('cat socket1.txt')
 Volume in drive C is Local Disk
 Volume Serial Number is D649-B68C

 Directory of C:\Users\aryan\PycharmProjects\classes

 Out[46]: 0

In [47]: dir (socket)
Out[47]:
['AF_APPLETALK',

【问题讨论】:

    标签: linux ipython


    【解决方案1】:

    你在这里混合了两个世界。

    一个是 Python 世界,您可以在其中调用 Python 函数(如 dir());在这个世界上,重定向不是简单地使用> 或类似的东西来完成的。

    另一个世界是Shell世界,你可以在其中调用shell命令行(如cat socket1.txt);在这个世界上,可以在命令后使用简单的> 符号(连同文件名)来完成重定向。使用system() 调用(或来自subprocess 模块的其他调用)进入这个世界。

    你现在做的是使用system()进入Shell世界,然后在这个世界中执行dir()(不起作用)。不过,重定向会起作用,因此您将创建一个名为 socket1.txt 的文件(可能为空)。

    重定向 Python 调用的输出通常不是一件容易的事。但是,您的情况很特殊:您只想将 Python 值转储到文件中。这很简单:

    with open('socket1.txt', 'w') as out_file:
      out_file.write(str(dir(socket)))
    

    【讨论】:

    • os.system('grep \'timeout\' socket1.txt') 由于某种原因也无法正常工作。以下是 socket1.txt 的截断输出。 'herror'、'htonl'、'htons'、'inet_aton'、'inet_ntoa'、'inet_ntop'、'inet_pton'、'io'、'ntohl'、'ntohs'、'os'、'selectors'、'setdefaulttimeout ', 'socket', 'socketpair', 'sys', 'timeout']
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    • 2015-10-30
    • 1970-01-01
    • 2019-12-19
    • 2011-06-04
    • 1970-01-01
    • 2013-09-17
    相关资源
    最近更新 更多