简体   繁体   English

在Python中执行和监视外部程序的多个实例

[英]Execute and monitor multiple instances of external program in Python

Main program is like this: 主程序是这样的:

PREPARE PARAMETERS FOR CHILD PROCESSES
subprocess.Popen('python child.py param=example1'.split(' '))
subprocess.Popen('python child.py param=example2'.split(' '))
...

How to make main program to monitor each instances of child process it launched and restart it with its corresponding parameters if it's not running. 如何使主程序监视它启动的子进程的每个实例,以及如何在未运行时使用其相应的参数重新启动它。

The purpose for keep multiple instances of child process running instead of implementing a multi-thread architect within main process is to utilize as much CPU and database throughputs as possible. 保持子进程的多个实例运行而不是在主进程中实现多线程架构师的目的是为了尽可能多地利用CPU和数据库的吞吐量。

Keep a dict with the .pid s of the child processes as keys, and the commandlines to restart them as corresponding values. 将子进程的.pid作为键保存命令,并使用命令.pid其重新启动作为对应值。 ie: 即:

childid = []
for cmdline in cmdlines:
  p = subprocess.Popen(cmdline.split())
  childid[p.pid] = cmdline

os.wait will return whenever any child process terminates: it gives you (pid, exitstatus) of the child. os.wait将在任何子进程终止时返回:它为您提供子进程(pid,exitstatus)。 So just restart appropriately and maintain childid . 因此,只需重新启动并保持childid ie: 即:

while mustcontinue:
  pid, exitstat = os.wait()
  cmdline = childid.pop(pid)
  p = subprocess.Popen(cmdline.split())
  childid[p.pid] = cmdline

Presumably you have some criteria for when this infinite loop ends, I just used mustcontinue as the name for those criteria here;-). 大概您对这个无限循环何时结束有一些标准,在这里我只是使用mustcontinue作为这些标准的名称;-)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM