从一个脚本运行多个Shell脚本,并在每次完成后执行一些操作

时间:2020-06-11 06:19:32

标签: python python-3.x subprocess daemon

我正在尝试编写python 守护程序 在某些情况下,将在相同时间下运行多个shell脚本 然后在每个任务完成

上执行一些操作
import time
import schedule
import subprocess


def spawn(name, count):
    cmd = 'some long lived shell process'
    proc = subprocess.Popen(cmd, shell=True, stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL, close_fds=True)
    consumers_dictionary[name] = proc


def thread_task():
    if someconditions
        spawn(name, count)


consumers_dictionary = {}
schedule.every(1).seconds.do(thread_task)
while 1:
    schedule.run_pending()
    time.sleep(1)

如何完成进程后如何控制proc状态并执行某些操作? 想我需要诺言之类的东西,还是检查我的每个字典proc对象的状态?

P.S。守护程序应该能够处理(运行和跟踪状态)多达500个进程

2 个答案:

答案 0 :(得分:1)

要检查子进程是否已终止,可以使用poll()类的Popen函数。如果返回的不是None,则子进程已终止。在while 1循环中睡眠一秒钟,您可以遍历进程的字典并poll进行操作,并确定终止时要做什么。

从您写问题的方式来看,我想这就是您想要的。如果您希望在子进程终止时获得某种中断,则看起来可能是可行的,但可能与平台有关。

答案 1 :(得分:0)

要等待以popen打开的进程,请使用wait。这是一个基于您的骨架的代码示例:

def spawn(name, count):

    processes = [] 
    cmd = 'ls -l ; sleep 2'
    for _ in range(count):
        proc = subprocess.Popen(cmd, shell=True, stdin=DEVNULL, stdout=DEVNULL, stderr=DEVNULL, close_fds=True)
        processes.append(proc)

    for proc in processes:
        res = proc.wait()
        print(f"process with pid {proc.pid} returned {res}")


def thread_task():
    if True:
        spawn(name = "dummy", count = 5)

schedule.every(1).seconds.do(thread_task)

while 1:
    schedule.run_pending()
    time.sleep(1)

结果如下:

process with pid 7784 returned 0
process with pid 7801 returned 0
process with pid 7802 returned 0
process with pid 7803 returned 0
process with pid 7805 returned 0
process with pid 7807 returned 0
...

请注意,您也可以使用poll来检查进程的状态,而无需等待进程完成。 (documentation