I have an executable called "foo" in "/home/myname/mydir/" and am trying to call it from Python, but I am doing something basic and wrong here. Can you help me?
import os, sys
sys.path.append("/home/myname/mydir/")
os.system("foo") # os.system("./foo") doesn't work either
Thanks
2 Answers 2
sys.path is the path to Python libraries, not the system PATH to search for binaries. Try changing os.environ['PATH'] instead.
>>> sys.path.append("/opt/local/bin")
>>> os.system("wget")
sh: wget: command not found
32512
>>> os.environ['PATH'] += os.pathsep + '/opt/local/bin'
>>> os.system("wget")
wget: missing URL
Comments
You'll want to use the subprocess module instead of os.system, for anything serious. For os.system, do this:
os.system('/home/myname/mydir/foo ')
For subprocess:
p = subprocess.Popen(['/home/myname/mydir/foo'])
p.communicate('')
if p.returncode != 0:
raise Exception('foo failed')
If you care about foo's argv[0] being 'foo' and not '/home/myname/mydir/foo', do this:
p = subprocess.Popen(['foo'], executable='/home/myname/mydir/foo')
The reason subprocess is so much better than os.system is that it provides better control over the argument list: it does not require the command line to be parsed by the shell, and that avoids a whole slew of potential security problems, particularly with user-supplied filenames and such. The other reason is that subprocess provides better handling of errors, and better redirection of stdin, stdout, and stderr. (Not shown in the example above.)