8

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.")
KeyPick
  • 103
  • 1
  • 2
  • 5

1 Answers1

4

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.
Adam Matan
  • 128,757
  • 147
  • 397
  • 562
  • You need to enter data to the `communicate` method. Will edit my answer soon. – Adam Matan Apr 10 '11 at 12:42
  • Thanks. I've added `exexfile('sub.py')` to the `communicate()` method, and now it runs the sub.py file, but in the same console so how do you get it to run seperately? I'm probably missing something really simple, sorry. Thanks again. – KeyPick Apr 10 '11 at 13:09
  • >> Once main.py has spawned sub.py it should terminate whilst sub.py continues to run. – geowar Feb 22 '13 at 01:30