Albert Mulder
Albert Mulder

Reputation: 167

Run subprocess to call another python script without waiting

I have read way to many threads now and really lost.

Just trying to do something basic before I make it complicated.

so i have a script test.py

I want to call the script from within runme.py but without waiting so it will process the other chunk of code, but then when it gets to the end wait for test.py code to finish before continuing on.

I cant seem to figure out the correct syntax for the p = subprocess.Popen (I have tried so many)

and do I need the that to the test.py if its in the same directory?

here is what i have but cant get to work.

import subprocess
p = subprocess.Popen(['python test.py'])
#do some code
p.wait()

Upvotes: 1

Views: 1872

Answers (1)

abarnert
abarnert

Reputation: 366123

I cant seem to figure out the correct syntax for the p = subprocess.Popen (I have tried so many)

You want to pass it a list of arguments. The first argument is the program to run, python (although actually, you probably want sys.executable here); the second is the script that you want python to run. So:

p = subprocess.Popen(['python', 'test.py'])

and do I need the that to the test.py if its in the same directory?

This will work the same way as if you ran python test.py at the shell: it will just pass test.py as-is to python, and python will treat that as a path relative to the current working directory (CWD).

So, if test.py is in the CWD, this will just work.

If test.py is somewhere else, then you need to provide either an absolute path, or one relative to the CWD.

One common thing you want is that test.py is in not necessarily in the CWD, but instead it's in the same directory as the script/module that wants to launch it:

scriptpath = os.path.join(os.path.dirname(__file__), 'test.py')

… or in the same directory as the main script used to start your program:1

scriptpath = os.path.join(os.path.dirname(sys.argv[0]), 'test.py')

Either way, you just pass that as the argument:

p = subprocess.Popen(['python', scriptpath])

1. On some platforms, this may actually be a relative path. If you might have done an os.chdir since startup, it will now be wrong. If you need to handle that, you want to stash os.path.abspath(os.path.dirname(sys.argv[0])) in the main script at startup, then pass it down to other functions for them to use instead of calling dirname(argv[0]) themselves.

Upvotes: 3

Related Questions