Entry
Is it possible for Python to call commands, e.g. "find, perl scripts, nmap, and others"?
Dec 18th, 2009 15:08
new acct, Joe Bloggs, unknown unknown, Sean Blakey
There are many ways to call other programs from python.
First, and simplest, is os.system. This simply fires off a sub-shell to
run the specified program, than returnsthe exit code of that program.
For example:
>>>import os
>>>os.system('wget ftp://ftp.python.org/pub/python/src/py152.tgz')
will download the python source distrobution.
If you want the output of a command (or want to write to a command on
stdin) you can use os.popen, which returns a python filehandle. For
example, to get a listing of allfiles ending in .mp3 on your system, you
can do:
>>import os
>>fd = os.popen('locate *.mp3')
>>filenames = fd.readlines()
You can also use popen to write to a process:
>>>import os
>>>fd = os.popen('/usr/sbin/sendmail nobody@localhost', 'w')
>>>fd.write('''Subject: test
this is a test.
''')
>>>fd.close()
Since you are working on a linux box, you probably also have access to
the popen2 module. This allows you to use coprocesses (giving you
access to both stdin and stdout of a process).
The popen2 module is documented at
http://www.python.org/doc/current/lib/module-popen2.html
Note that os.popen works unreliably on Windows boxes, and the popen2
module is unix-specific.