prev | Version 1034 (Mon Nov 27 20:46:07 2006) | next |
subprocess
module lets you run external programsPopen
Popen("cmd")
, where "cmd"
is the program to be runstdin
, stdout
, stderr
, working directory, and environment variablesimport subprocess subprocess.Popen("date")
Mon Apr 3 09:05:39 EST 2006
Popen
a listimport subprocess subprocess.Popen(["date", "-u"])
Mon Apr 3 13:06:27 EST 2006
cwd
parameter)env
parameter)Popen
's stdout
parameter to PIPE
stdout
memberimport subprocess SQL = 'select * from Person' child = subprocess.Popen(['sqlite3', 'experiment.db', SQL], stdout=subprocess.PIPE) lines = child.stdout.readlines() for line in lines: line = line.strip().split('|') print '%s %s (%s)' % (line[1], line[2], line[0])
Kovalevskaya Sofia (skol) Lomonosov Mikhail (mlom) Mendeleev Dmitri (dmitri) Pavlov Ivan (ivan)
stdin
to PIPE
zlib
, gzip
, or bz2
librariesdef pipe_write(filename, lines): child = subprocess.Popen(['gzip', '-c'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) for line in lines: child.stdin.write(line) child.stdin.close() result = child.stdout.read() return result
gzip -c
-c
meaning “write result to standard output”stdin
stdout
Popen.communicate
stdin
stdout
and stderr
at the same timePyObject
python.h
to get its definitionFigure 22.1: PyObject
self
is NULL
for pure functions, and an object for methodsargs
is a variable-length list of argumentsPyArg_ParseTuple
to extract arguments' valuesNULL
to signal errorPy_BuildValue
to build a Python structure with the result value/* Triple an integer value. */ static PyObject * triple(PyObject * self, PyObject * args) { int val; if (!PyArg_ParseTuple(args, "i", &val)) { return NULL; } val = val * 3; return Py_BuildValue("i", val); }
/* Table of module contents (handed back to Python at initialization). */ static PyMethodDef contents[] = { {"triple", triple, METH_VARARGS}, {NULL, NULL} }; /* Initialization function. */ void inittriple() { Py_InitModule("triple", contents); }
contents
has one entry for each functioninitXYZ
for the module XYZ
Py_InitModule
to pass the table of module contents to the interpreter.dll
on Windows.so
on Unix)import triple print triple.triple(11)
33
Boost.Python
does the best it can (which is pretty good)SWIG
(the Simple Wrapper Interface Generator)triple
, put the following in triple.i
/* triple.i */ %module triple %{ extern int triple(int n); %}
SWIG
can also generate wrappers for Perl, Java, and other high-level languagesF2PY
and Pyfort
)import stuff
?PYTHONPATH
for stuff.py
module
object to keep track of the things just compiledFigure 22.2: Loading a Module
__import__
function to load a filevars
to find out what a module object containsimport sys, os def list_contents(module_name): print module_name if os.path.dirname(module_name) not in sys.path: sys.path.append(os.path.dirname(module_name)) try: module = __import__(module_name) for name in vars(module): print '\t' + name except ImportError: print >> sys.stderr, 'Unable to import %s' % module_name if __name__ == '__main__': for module_name in sys.argv[1:]: list_contents(module_name)
$ python lister.py lister
lister
__builtins__
__name__
__file__
list_contents
__doc__
sys.path
not something you should do in general…def loader(config_file): result = {} imported = {} infile = open(config_file, 'r') for line in config_file: name, module, func = line.split() if name in result: raise LoaderError('Trying to set name %s twice', name) if module not in imported: imported[module] = __import__(module) if func not in imported[module]: raise LoaderError('Function %s not in module %s', func, module) result[name] = func return result
globals
returns a dictionary of global variables$ python
Python 2.4.1 (#1, May 27 2005, 18:02:40)
[GCC 3.3.3 (cygwin special)] on cygwin
>>> G = globals() >>> G{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'G': {...}}
>>> a = 1 >>> G{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', 'a': 1, '__doc__': None, 'G': {...}}
>>> del G['a'] >>> G{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'G': {...}}
>>> G['b'] = 2 >>> G{'b': 2, 'G': {...}, '__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None}
>>> def double(x): ... return 2 * x ... >>> G['d'] = double >>> del G['double'] >>> d<function double at 0x4d68b4>
>>> G{'b': 2, 'd': <function double at 0x4d68b4>, 'G': {...}, '__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None}
prev | Copyright © 2005-06 Python Software Foundation. | next |