[IPython-user] Capturing output from shell cmds
Fernando Perez
fperez at colorado.edu
Mon Aug 18 20:22:09 CDT 2003
Ero Carrera wrote:
>> Hello,
>>
>> I've just started to look into IPython and seems to have an incredible
>> potential.
>> But one thing I find it lacks (if it does) is the ability to capture the
>> output from the executed shell commands. I found and modified a script
>> to do so, but I'm curious to know whether I'm duplicating an already
>> existing feature.
Place the stuff at the bottom in a python file in your ~/.ipython directory,
and set your ipythonrc file to load it with execfile:
execfile YOURFILE.py
This will define @capture as a new magic function which will capture and
return the output from any shell command.
You can then set this to a variable assigning to _.
Example:
In [8]: capture ls
Out[8]:
'inner.py\ninner.pyc\nMakefile\nmat_ten_inner_bz.h\nmat_ten_inner_dim_expand.h\nmat_ten_inner_np.h\nREADME\ntiming.py\n_utils.cpp\n_utils.o\n_utils.so'
In [9]: out = _
In [10]: print out
inner.py
inner.pyc
Makefile
mat_ten_inner_bz.h
mat_ten_inner_dim_expand.h
mat_ten_inner_np.h
README
timing.py
_utils.cpp
_utils.o
_utils.so
Note that I'm just using commands.getoutput, a standard python module which
you can use yourself to directly capture the output:
In [11]: out = commands.getoutput('ls')
In [12]: print out
inner.py
inner.pyc
Makefile
mat_ten_inner_bz.h
mat_ten_inner_dim_expand.h
mat_ten_inner_np.h
README
timing.py
_utils.cpp
_utils.o
_utils.so
So the magic @capture doesn't really add much which isn't in python to begin
with
Best,
f.
######### YOURFILE.py ################################
import commands
# fisrt define a function with the proper form:
def magic_capture(self,parameter_s=''):
"""Capture the output of system commands and return as a string"""
return commands.getoutput(parameter_s)
# Add the new magic function to the class dict:
from IPython.iplib import InteractiveShell
InteractiveShell.magic_capture = magic_capture
# And remove the global name to keep global namespace clean. Don't worry, the
# copy bound to IPython stays, we're just removing the global name.
del magic_capture
More information about the IPython-user
mailing list