How do I spawn a separate python process?

KeyPick picture KeyPick · Apr 10, 2011 · Viewed 9k times · Source

I need to spawn a separate python process that runs a sub script.

For example:

main.py runs and prints some output to the console. It then spawns sub.py which starts a new process. Once main.py has spawned sub.py it should terminate whilst sub.py continues to run.

Thank you.

Edit:

When I run main.py it prints 'main.py' but nothing else and sub.py doesn't launch.

main.py

print "main.py"

import subprocess as sp
process=sp.Popen('sub.py', shell=True, stdout=sp.PIPE, stderr=sp.PIPE)
out, err = process.communicate(exexfile('sub.py'))  # The output and error streams

raw_input("Press any key to end.")

sub.py

print "sub.py"
raw_input("Press any key to end.")

Answer

Adam Matan picture Adam Matan · Apr 10, 2011

execfile

The straightforward approach:

execfile('main.py')

Subprocess

Offers fine-grained control over input and output, can run processes in background:

import subprocess as sp
process=sp.Popen('other_file.py', shell=True, stdout=sp.PIPE, stderr=sp.PIPE)
out, err = process.communicate()  # The output and error streams.