我在用着subprocess.Popen
启动多个进程。
代码是这样的:
while flag > 0:
flag = check_flag()
c = MyClass(num_process=10)
c.launch()
MyClass
如果类似以下内容:
MyClass(object)
def __init__(self, num_process):
self.num_process = num_process
def launch(self):
if self.check_something() < 10:
for i in range(self.num_process):
self.launch_subprocess()
def launch_subprocess(self):
subprocess.Popen(["nohup",
"python",
"/home/mypythonfile.py"],
stdout=open('/dev/null', 'w'),
stderr=open('logfile.log', 'w'),
shell=False)
在大多数情况下,启动的子进程会终止,有时会在运行过程中终止。在某些情况下,它会完成。
但是,如果我使用subprocess.Popen
直接在 while 循环中,该过程继续并及时完成。
有人可以告诉我如何按照上面描述的方式使用子进程来让进程在后台运行吗?
The nohup
仅当您的主进程正常退出时才停止 SIGHUP 信号。对于 SIGINT 或 SIGTERM 等其他信号,子进程会收到与父进程相同的信号,因为它位于同一进程组中。有两种使用 Popen 的方法preexec_fn
争论。
设置子进程组:
subprocess.Popen(['nohup', 'python', '/home/mypythonfile.py'],
stdout=open('/dev/null', 'w'),
stderr=open('logfile.log', 'a'),
preexec_fn=os.setpgrp )
更多信息在另一个post.
使子进程忽略这些信号:
def preexec_function():
signal.signal(signal.SIGINT, signal.SIG_IGN)
subprocess.Popen( ... , preexec_fn=preexec_function)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)