简体   繁体   English

使用多处理检测多个子进程的终止

[英]Detecting termination of multiple child processes with multiprocessing

#!/usr/bin/python
import os

from os import getpid

import multiprocessing


build="613719"
file1=open('/auto/home/venkam11/python/install-script/build-ddr-file.txt', 'r')

def installation(model,ddr,build):

    cli = "/auto/tools/qa/shared/qa-branch/util/install.pl -durham -restart -silentinstall -model %s -branch 6.2A %s %s"  %(model, ddr, build)

    print cli
    os.popen2(cli)
    print "installation has started on %s \n" %ddr

if name == ' main ':如果名称== ' main ':

pid=getpid()

print("parent process id :{}".format(getpid()))

for ddr in file1:
    print ddr.rstrip()
    if 'dd4500' in ddr:
        print "dd4500"
        model = "dd4500"
    elif ('apollo' or 'apolloplus') in ddr:
        print "dd9500"
        model = "dd9500"
    elif 'dd2500' in ddr:
        print "dd2500"
        model = "dd2500"
    elif 'dd7200' in ddr:
        print "dd7200"
        model = "dd7200"
    elif 'jupiter' in ddr:
        print "dd9800"
        model = "dd9800"
    ddr = ddr.rstrip()
    ins=multiprocessing.Process(target=installation, args=(model,ddr,build))
    ins.start()

Basically iam trying to read the file which has the machine names and using multiprocessing, I want to insatll the OS on the machines which I have read.基本上我试图读取具有机器名称的文件并使用多处理,我想在我读过的机器上安装操作系统。

Above is my code, when I run, it starts installing on all the machines at once and the main program terminates.以上是我的代码,当我运行时,它立即开始在所有机器上安装并且主程序终止。

But I want the main program not to terminate, it has to wait until the child process finish the job, also return the output saying the child process job is complete.但我希望主程序不要终止,它必须等到子进程完成作业,并返回输出说子进程作业完成。

Install make take anytime 1 hr or 2 hrs, but I want the message saying that all the process jobs are completed.安装 make 需要 1 小时或 2 小时,但我希望显示所有流程作业已完成的消息。

Can anyone please help here.任何人都可以在这里帮忙。

Populate a list of processes and use join() to join them with the parent process and then print the message.填充进程列表并使用join()将它们与父进程连接,然后打印消息。 This way, the parent waits till the children are done with their tasks before executing the lines that follow.这样,父进程会等到子进程完成他们的任务,然后再执行后面的行。

The code for the same should look something like this:相同的代码应该如下所示:

#!/usr/bin/python
import os
import multiprocessing
import subprocess
import time
import sys

from os import getpid

file1 = open('/auto/home/venkam11/python/install-script/build-ddr-file.txt', 'w+')
print ("enter the ddr names one by one in each line and press ctrl-d twice")
userInput = sys.stdin.readlines()
file1.writelines(userInput)
file1.close()
build = input("\nenter the build number : \n")
branch = raw_input("enter the branch name  : " )
file1 = open('/auto/home/venkam11/python/install-script/build-ddr-file.txt', 'r')

def installation(model, branch, ddr, build, shared_dict):
        cli = "/auto/tools/qa/shared/qa-branch/util/install.pl -durham -restart -silentinstall -model %s -branch %s %s %s"  %(model, branch, ddr, build)
        print cli
        print "installation has started on %s \n" % ddr
        time.sleep(20)
        try:
            subprocess.check_call(cli, shell=True)
            shared_dict[ddr] = True
        except subprocess.CalledProcessError:
            shared_dict[ddr] = False

if __name__ == '__main__':
    #pid=getpid()
    #print("parent process id : {}".format(getpid()))
    processes = []
    manager = multiprocessing.Manager()
    shared_dict = manager.dict()
    for ddr in file1:
        print ddr.rstrip()
        if 'dd4500' in ddr:
            print "dd4500"
            model = "dd4500"
        elif ('apollo' or 'apolloplus') in ddr:
            print "dd9500"
            model = "dd9500"
        elif 'dd2500' in ddr:
            print "dd2500"
            model = "dd2500"
        elif 'dd7200' in ddr:
            print "dd7200"
            model = "dd7200"
        elif 'jupiter' in ddr:
            print "dd9800"
            model = "dd9800"

        ddr = ddr.rstrip()
        ins = multiprocessing.Process(target=installation, args=(model, branch, ddr, build, shared_dict))
        ins.start()
        processes.append(ins)

    for process in processes:
        process.join()

    print('All the installations are complete')
    print('Details: ')
    for ddr, success in shared_dict.items():
        if success:
            print('Installation on {} successful'.format(ddr))
        else:
            print('Installation on {} unsuccessful'.format(ddr))

Welcome to Stackoverflow.欢迎使用 Stackoverflow。 Much like threads, the easiest way to synchronise with your subprocesses is to join() them, most usually in the creating thread/process.与线程非常相似,与子进程同步的最简单方法是join()它们,最常见的是在创建线程/进程中。 The os.popen2 call was deprecated when the subprocess module was introduced, as it does not give the necessary degree of control over and communication with the started subprocess.os.popen2的电话时,已弃用subprocess被引入模块,因为它没有给过控制,并与启动子通信的必要程度。 For that you have correctly deduced you can use the multiprocessing module.为此,您已经正确推断出您可以使用multiprocessing模块。

The technical answer to your question using multiprocessing is already covered well in another answer, as well as in this question , which explains how the calling entity can synchronise with its child processes.使用multiprocessing对您的问题的技术答案已经在另一个答案以及本问题中得到了很好的介绍,它解释了调用实体如何与其子进程同步。 It's quite permissible to deal with an unknown number of subprocesses by storing each one in a list, for example, like this通过将每个子进程存储在列表中来处理未知数量的子进程是完全允许的,例如,像这样

for p in my_processes:
    p.join()

A more useful answer might be that the subprocess module allows creation and monitoring of other processes without the overhead and complexity of multiprocessing , which has advanced features for inter-process communication that you do not (yet) appear to need.一个更有用的答案可能是subprocess模块允许创建和监视其他进程,而没有multiprocessing的开销和复杂性,它具有您(还)似乎不需要的进程间通信的高级功能。 Its documentation has quite good examples of how older and/or less appropriate Python code can be adapted to use the new module, so it could be worth a look.它的文档有很好的示例,说明如何调整旧的和/或不太合适的 Python 代码以使用新模块,因此值得一看。

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

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