How do I spawn a separate python process?

末鹿安然 提交于 2019-12-22 06:24:18

问题


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.")

回答1:


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.


来源:https://stackoverflow.com/questions/5611576/how-do-i-spawn-a-separate-python-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!