Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I spawn a separate python process?

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.")
like image 883
KeyPick Avatar asked Apr 10 '11 11:04

KeyPick


1 Answers

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.
like image 177
Adam Matan Avatar answered Oct 13 '22 10:10

Adam Matan