进程和子进程之间的通信

时间:2018-04-06 09:00:37

标签: python python-2.7 multiprocessing

我有一个小的多进程程序,并期待订单会 以下方式。

hello number
ls -l <output>

但它无效。所以我认为父进程不了解子进程。 主进程如何等待完成子进程。或者我错过了非常基本的 多处理的概念

#!/usr/bin/env python
import multiprocessing
import subprocess

def run_command():
    pipe = subprocess.Popen("ls -l", stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE,
                                    shell=True)
    out, err = pipe.communicate()
    pipe.wait()
    print out, err

def msg(number):
    print "hello %s" %(number)
    run_command()

def main():
    print "yes"
    procs = []
    for i in range(0, 100, 1):
        process = multiprocessing.Process(target=msg, args=(i,))
        procs.append(process)
    for proc in procs:
        proc.start()
    for proc in procs:
        proc.join()

if __name__ == "__main__":
    main()

Expected code:
hello 0
total 4
-rw-rw-r-- 1 goswamia <#> 682 Apr  6 02:51 check_process.py

hello 1
total 4
-rw-rw-r-- 1 goswamia <#> 682 Apr  6 02:51 check_process.py

etc

获取输出: python check_process.py

yes
hello 0
hello 1
hello 2
hello 3
hello 4
total 4
-rw-rw-r-- 1 goswamia <#> 682 Apr  6 02:51 check_process.py

total 4
-rw-rw-r-- 1 goswamia <#> 682 Apr  6 02:51 check_process.py

total 4
-rw-rw-r-- 1 goswamia <#> 682 Apr  6 02:51 check_process.py

total 4
-rw-rw-r-- 1 goswamia <#> 682 Apr  6 02:51 check_process.py

total 4
-rw-rw-r-- 1 goswamia <#> 682 Apr  6 02:51 check_process.py

2 个答案:

答案 0 :(得分:0)

我能够离开,但无法理解以下行。如果我评论输出的顺序不正确

,它到底在做什么

psutil.Process(proc.pid).children()(无法理解这一点)

WHERE [Product Description] LIKE '%[0-9][0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]%' OR [Product Description] LIKE  '%[0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]%'

答案 1 :(得分:-1)

似乎没有使用pipe.wait()

  

编辑:miss of pipe.wait()你应该放置你的pipe.wait()   就像这个编辑过的代码一样

这是您编辑的代码

#!/usr/bin/env python
import multiprocessing
import subprocess


def msg(number):
    # this command for sub process
    pipe = subprocess.Popen("ls -l", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

    # this command that runing in main process
    out, err = pipe.communicate()
    print "hello %s" %(number)
    print out, err

    # this make sub prosses waits for the command in main process to finish
    pipe.wait()

def main():
    print "yes"
    procs = []
    for i in range(0, 5, 1):
        process = multiprocessing.Process(target=msg, args=(i,))
        procs.append(process)
    for proc in procs:
        proc.start()
    for proc in procs:
        proc.join()

if __name__ == "__main__":
    main()

该命令将遵循什么是

hello number
ls -l <output>

其他人已经解释了这个Using subprocess module to work in parallel (Multi-process)

您的第一个代码在单独的进程中执行,输出无序,因为后台进程和前台进程也是单独的进程。

相关问题