Python to call commands, e.g. "find , perl scripts , nmap , and others" is this possible?

Sean Blakey sblakey at freei.net
Thu Jun 1 14:07:54 EDT 2000


On Thu, Jun 01, 2000 at 11:44:43AM -0500, Jim wrote:
>   
>   
> Dear list, 
> 
> I'm new to Python, and I'm sorry if I'm asking about anything that has
> been 
> already discussed. 
> 
> 
> I would like to use Python to call commands, e.g. "find , perl scripts
> , nmap , and others" is this possible? 
> 
> 
> I do not need GUI. All I need is to link the out put and work with it.
> Is perl or shell scripts my only 
> answer? 
> 
> 
> jim 
> 
> -- 
> 
> Proprietary & Confidential.  The information transmitted is intended
> only for the person or entity to whom it is addressed and may
> 
> contain confidential and/or privileged material.  Any review,
> retransmission, dissemination, or other use of, or taking of any
> 
> action in reliance upon, this information by persons or entities other
> than the intended recipient is prohibited.  If you received this in
> error, please
> 
> contact the sender and delete the material from any computer.
>  

Jim,

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
>>import string
>>fd = os.popen('locate *.mp3')
>>filenames = string.split(fd.read, '\n')
You can also use popen to write to a process:
>>>import os
>>>fd = os.popen('/usr/sbin/sendmail nobody at 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 unreliablyon Windows boxen, and the popen2
odule is unix-specific.
    -Sean

-- 
Sean Blakey, sblakey at freei.com
Software Developer, FreeInternet.com
(253)796-6500x1025
"Everyone is entitled to an *informed* opinion."
-- Harlan Ellison




More information about the Python-list mailing list