Using subprocess to run Python script on Windows Using subprocess to run Python script on Windows windows windows

Using subprocess to run Python script on Windows


Just found sys.executable - the full path to the current Python executable, which can be used to run the script (instead of relying on the shbang, which obviously doesn't work on Windows)

import sysimport subprocesstheproc = subprocess.Popen([sys.executable, "myscript.py"])theproc.communicate()


How about this:

import sysimport subprocesstheproc = subprocess.Popen("myscript.py", shell = True)theproc.communicate()                   # ^^^^^^^^^^^^

This tells subprocess to use the OS shell to open your script, and works on anything that you can just run in cmd.exe.

Additionally, this will search the PATH for "myscript.py" - which could be desirable.


Yes subprocess.Popen(cmd, ..., shell=True) works like a charm. On Windows the .py file extension is recognized, so Python is invoked to process it (on *NIX just the usual shebang). The path environment controls whether things are seen. So the first arg to Popen is just the name of the script.

subprocess.Popen(['myscript.py', 'arg1', ...], ..., shell=True)