将 python/ipython 交互式提示命令的输出重定向到文件或变量

Redirect output of python/ipython interactive prompt commands to files or variables

如果我在 Python 或 Ipython 命令提示符处执行函数,例如 'help(dir)':

>>> help(dir)
Help on built-in function dir in module __builtin__:

dir(...)
    dir([object]) -> list of strings

    If called without an argument, return the names in the current scope.

我想在文件或变量中捕获结果输出,但是

>>> x = help(dir)        
>>> help(dir) >file.txt   
>>> help(dir) >>file.txt

不工作。我看到了一个相关的问题(Redirect an output command to a variable or file?),虽然它非常复杂,但很难即时记住,而且不清楚它是否适用于此。

在 bash shell 中,可以使用 > 或 2> 重定向输出。似乎在 Python 或 Ipython shell.

中做类似的事情应该很容易

使用IPythoncapture_output函数

In [21]: from IPython.utils import io

In [22]: with io.capture_output() as captured:
   ....:   help(dir)
   ....:   

In [23]: print captured.stdout
Help on built-in function dir in module __builtin__:

dir(...)
    dir([object]) -> list of strings

    If called without an argument, return the names in the current scope.

更新

如果上述解决方案不起作用,您可以使用ipython 命令输出捕获功能。例如:

In [6]: output = !python -c 'help(dir)' | cat

In [7]: output
Out[7]: 
['Help on built-in function dir in module __builtin__:',
 '',
 'dir(...)',
 '    dir([object]) -> list of strings',

甚至比上面的方法更好(两者都有效),因为更容易记住并且不需要导入,是 iPython 魔法 %%capture:

In [38]: %%capture myout
   ....: help(dir)
   ....:

In [39]: print myout.stdout
Help on built-in function dir in module __builtin__:

dir(...)
    dir([object]) -> list of strings

    If called without an argument, return the names in the current scope.
    Else, return an alphabetized list of names comprising (some of) the attributes 
    of the given object, and of attributes reachable from it.
    If the object supplies a method named __dir__, it will be used; otherwise
    the default dir() logic is used and returns:
      for a module object: the module's attributes.
      for a class object:  its attributes, and recursively the attributes
        of its bases.
      for any other object: its attributes, its class's attributes, and
        recursively the attributes of its class's base classes.