Tom*_*ker 8 python command-line ipython
如果我在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.
Run Code Online (Sandbox Code Playgroud)
我想在文件或变量中捕获结果输出,但是
>>> x = help(dir)
>>> help(dir) >file.txt
>>> help(dir) >>file.txt
Run Code Online (Sandbox Code Playgroud)
不工作.我看到一个相关的问题(将输出命令重定向到一个变量或文件?)虽然它非常复杂,很难在运行中记住,并且不清楚它是否适用于此处.
在bash shell中,可以使用>或2>重定向输出.看起来在Python或Ipython shell中应该很容易做类似的事情.
Ste*_*nes 11
iPython magic %% 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.
Run Code Online (Sandbox Code Playgroud)
使用IPython capture_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.
Run Code Online (Sandbox Code Playgroud)
更新
如果上述解决方案不起作用,您可以使用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',
Run Code Online (Sandbox Code Playgroud)