执行" shell"来自python的子命令&多

时间:2017-09-19 03:05:33

标签: python shell

我目前正在使用子进程和多处理从python启动serialals shell命令。这里的代码不是真实的,但类似的:

    def fakeFunc(cmd):
        print("the pid "+str(os.getpid())+"begin", end=":")
        process=Popen(cmd, stdout=PIPE, shell=True, stderr=STDOUT)
        for line in iter(process.stdout.readline,b''):
            line_str=line.decode(sys.stdout.encoding)
            ##### analyse line_str######
    with Pool() as pool:
        cmds=['mkdir -p /home/jeff/workspace/zebu/compile/vdv && cd /home/jeff/workspace/zebu/compile/vdv && compile', 'mkdir -p /home/jeff/workspace/zebu/compile/vdr && cd /home/jeff/workspace/zebu/compile/vdr && compile', 'mkdir -p /home/jeff/workspace/zebu/compile/rdv && cd /home/jeff/workspace/zebu/compile/rdv && compile']
        pool.map_async(fakeFunc, cmds)
        pool.close()
        pool.join()

似乎只有cmds中的最后一个已执行,其他三个在print("the pid "+str(os.getpid())+"begin", end=":")之后跳出了函数。任何帮助表示赞赏

1 个答案:

答案 0 :(得分:0)

使用cathing Exception将你的fakeFunc的主体包裹到try-except,这样你就可以发现那里发生了什么错误。

def fakeFunc(cmd):
    try:
        print("the pid " + str(os.getpid()) + " begin", end=":\n")
        process = Popen(cmd, stdout=PIPE, shell=True, stderr=STDOUT)
        for line in iter(process.stdout.readline, b''):
            line_str = line.decode(sys.stdout.encoding)
            ##### analyse line_str######
    except Exception as e:
        print(e)

with Pool() as pool:
    cmds=['mkdir -p /home/jeff/workspace/zebu/compile/vdv && cd /home/jeff/workspace/zebu/compile/vdv && compile', 'mkdir -p /home/jeff/workspace/zebu/compile/vdr && cd /home/jeff/workspace/zebu/compile/vdr && compile', 'mkdir -p /home/jeff/workspace/zebu/compile/rdv && cd /home/jeff/workspace/zebu/compile/rdv && compile']
    pool.map_async(fakeFunc, cmds)
    pool.close()
    pool.join()