[Tutor] Newbie Question Again.
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Sun, 9 Jun 2002 00:00:00 -0700 (PDT)
On Sat, 8 Jun 2002, SA wrote:
> I'm running Python on Mac OSX. (bsd based system) How do I call a
> program from outside Python to be run from within my Python script/ In
> other words if I have an executable file, say "someprogram", how would I
> execute this program from within a python script.
Hi SA,
We can use the os.system() call to run external commands. For example:
###
import os
print "The return code from os.system('ls') is", os.system('ls')
###
will run the 'ls' command, and give back to us a errorlevel value.
If we want to grab the 'standard out' output of that external program,
then the os.popen() command is more useful. Here's an example:
###
>>> process_file = os.popen('ls -l gift/')
>>> process_file.readline()
'total 36\n'
>>> print process_file.read()
-rw-r--r-- 1 dyoo dyoo 1598 May 22 22:25 directed_point.py
-rw-r--r-- 1 dyoo dyoo 3573 May 22 22:35 directed_point.pyc
-rw-r--r-- 1 dyoo dyoo 1628 May 22 22:26 main.py
-rw-r--r-- 1 dyoo dyoo 2647 May 22 22:25 names.py
-rw-r--r-- 1 dyoo dyoo 3691 May 22 22:35 names.pyc
-rw-r--r-- 1 dyoo dyoo 3377 May 22 22:25 starfield.py
-rw-r--r-- 1 dyoo dyoo 3598 May 22 22:35 starfield.pyc
-rw-r--r-- 1 dyoo dyoo 2010 May 22 22:25 three_d.py
-rw-r--r-- 1 dyoo dyoo 3590 May 22 22:35 three_d.pyc
###
If you want to read more about these functions, you can find more details
in the Python Standard Library. Here's are some links you might find
useful:
http://www.python.org/doc/lib/os-procinfo.html
http://www.python.org/doc/lib/os-newstreams.html
http://www.python.org/doc/lib/module-popen2.html
(There are some other functions with the name 'exec...' in the 'os'
module, but they're probably not what you want: the 'exec...' functions
end up actually replacing the Python program altogether --- Python
reliquishes complete control to the 'exec'ed program.)
If you have more questions, please feel free to ask. Hope this helps!