gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:42:08 24 4
gpt4 key购买 nike

如果我在 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 中做类似的事情应该很容易。

最佳答案

比上面的方法(两者都有效)更好的是 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.

关于python - 将python/ipython交互式提示命令的输出重定向到文件或变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28169697/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com