将python / ipython交互式提示命令的输出重定向到文件或变量 [英] Redirect output of python/ipython interactive prompt commands to files or variables

查看:789
本文介绍了将python / ipython交互式提示命令的输出重定向到文件或变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I execute a function at the Python or Ipython command prompt, such as '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.

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

I'd like to capture the resulting output in a file or variable, but

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

不起作用。我看到一个相关问题(将输出命令重定向到变量或文件?)尽管它非常复杂,但很难记住,并且不清楚它是否适用于此处。

do not work. I see a related question (Redirect an output command to a variable or file?) though it is awfully complicated, would be difficult to remember on the fly, and it unclear whether it even applies here.

在bash shell中,输出可以用>或2>重定向。看起来在Python或Ipython shell中应该很容易做类似的事情。

In the bash shell, output can be redirected with > or 2>. Seems like it should be easy to do something similar in the Python or Ipython shell.

推荐答案

使用IPython capture_output function

Use IPython capture_output function

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 case above solution does not work, you can use ipython command output capture feature. E.g.:

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',

这篇关于将python / ipython交互式提示命令的输出重定向到文件或变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆