[IPython-dev] Shell capture magic introduced
Fernando Perez
fperez at colorado.edu
Tue Jan 6 17:17:34 EST 2004
Hi all,
after reading over all of your feedback (many thanks to all who responded) and
actually needing the functionality for some work today, I decided to implement
the shell capture system as a magic function. This cleans up the code (no new
special syntax to worry about), and it makes the feature nicely fit within the
existing framework.
I called it sc (short for shell capture), deliberately choosing a very short
name to minimize typing. This is a compromise to having a special syntax,
which I feel balances well typing efficiency with simplicity.
I've put the code already into CVS, and removed the exploratory $var=cmd
functionality. Below is how it currently works, copied straight from an
ipython session. Comments and suggestions are welcome before the 0.6 release.
Regards,
Fernando.
############# IPython session output:
In [1]: pdoc sc
Shell capture - execute a shell command and capture its output.
@sc [options] varname=command
IPython will run the given command using commands.getoutput(), and
will then update the user's interactive namespace with a variable
called varname, containing the value of the call. Your command can
contain shell wildcards, pipes, etc.
The '=' sign in the syntax is mandatory, and the variable name you
supply must follow Python's standard conventions for valid names.
Options:
-l: list output. Split the output on newlines into a list before
assigning it to the given variable. By default the output is stored
as a single string.
-v: verbose. Print the contents of the variable.
In [2]: sc a=ls *sin*
In [3]: sc -v a=ls *sin*
a ==
'ftest_sin16_1d.c\nftest_sin_1d.c\nftest_sin2_1d.c\nftest_sin2_2d.c\nftest_sin2_3d.c\nftest_sin_2d.c\nftest_sin_3d.c\nftest_sin64_1d.c'
In [4]: sc -l -v a=ls *sin*
a ==
['ftest_sin16_1d.c',
'ftest_sin_1d.c',
'ftest_sin2_1d.c',
'ftest_sin2_2d.c',
'ftest_sin2_3d.c',
'ftest_sin_2d.c',
'ftest_sin_3d.c',
'ftest_sin64_1d.c']
# You can capture a file as lines trivially:
In [5]: sc -l -v g=cat ftest_gauss_sharp_1d.c
g ==
['#include <math.h>',
'',
'static double dsqrarg;',
'#define DSQR(a) ((dsqrarg=(a)) == 0.0 ? 0.0 : dsqrarg*dsqrarg)',
'',
'// Globals',
'const double alpha = 100000; // Width of the Gaussian',
'',
'#define FUNCTION_NAME ftest_gauss_sharp',
'#define NDIM 1',
'',
'double FUNCTION_NAME(double x) {',
' double r2 = DSQR(x-0.5);',
' return exp(-alpha*r2);',
'}']
# You can even use pipes:
In [14]: sc -v a=grep NAME *.c | grep const
a ==
'ftest_const_1d.c:#define FUNCTION_NAME ftest_const\nftest_const_1d.c:double
FUNCTION_NAME(double x) {'
More information about the IPython-dev
mailing list