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.
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.
Redirect Output to a File Only To redirect the output of a command to a file, type the command, specify the > or the >> operator, and then provide the path to a file you want to the output redirected to. For example, the ls command lists the files and folders in the current directory.
When the notation > > filename is added to the end of a command, the output of the command is appended to the specified file name, rather than writing over any existing data. The >> symbol is known as the append redirection operator.
Even better than the methods above, (both of which will work), as much easier to remember and no imports needed, is the 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.
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.
Update
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',
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With