如何生成一个单独的 python 进程? [英] How do I spawn a separate python process?
本文介绍了如何生成一个单独的 python 进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要生成一个单独的运行子脚本的 python 进程.
I need to spawn a separate python process that runs a sub script.
例如:
main.py 运行并将一些输出打印到控制台.然后它生成 sub.py,它启动一个新进程.一旦 main.py 产生了 sub.py,它应该终止,而 sub.py 继续运行.
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.
谢谢.
当我运行 main.py 时,它会打印main.py",但没有其他内容,并且 sub.py 不会启动.
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.")
子.py
print "sub.py"
raw_input("Press any key to end.")
推荐答案
execfile
直截了当的方法:
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.
这篇关于如何生成一个单独的 python 进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文