user2340760
user2340760

Reputation: 51

Running another python script with os.system

I have old python. So can't use subprocess. I have two python scripts. One primary.py and another secondary.py. While running primary.py I need to run secondary.py.

Format to run secondary.py is 'python secondary.py Argument'

os.system('python secondary.py Argument')...is giving error saying that can't open file 'Argument': [Errno 2] No such file or directory

Upvotes: 2

Views: 28255

Answers (2)

ddzialak
ddzialak

Reputation: 1080

Which python version do you have? Could you show contents of your secondary.py ? For newer version it seems to work correctly:

ddzialak@ubuntu:$ cat f.py 
import os
os.system("python s.py Arg")

ddzialak@ubuntu:$ cat s.py

print "OK!!!"
ddzialak@ubuntu:$ python f.py
OK!!!
ddzialak@ubuntu:$ 

Upvotes: 0

abarnert
abarnert

Reputation: 365747

Given the code you described, this error can come up for three reasons:

  • python isn't on your PATH, or
  • secondary.py isn't in your current working directory.
  • Argument isn't in your current working directory.

From your edited question, it sounds like it's the last of the three, meaning the problem likely has nothing to do with system at all… but let's see how to solve all three anyway.

First, you want a path to the same python that's running primary.py, which is what sys.executable is for.

And then you want a path to secondary.py. Unfortunately, for this one, there is no way (in Python 2.3) that's guaranteed to work… but on many POSIX systems, in many situations, sys.argv\[0\] will be an absolute path to primary.py, so you can just use dirname and join out of os.path to convert that into an absolute path to secondary.py.

And then, assuming Argument is in the script directory, do the same thing for that:

my_dir = os.path.dirname(sys.argv[0])
os.system('%s %s %s' % (sys.executable, 
                        os.path.join(my_dir, 'secondary.py'),
                        os.path.join(my_dir, 'Argument')))

Upvotes: 1

Related Questions