捕获check_output值

时间:2015-05-28 20:54:44

标签: python multiprocessing

我试图捕获check_output的返回值,而不是让它自动打印到命令行。不幸的是,我的解决方案不起作用,我不知道为什么。我已经包含了我的代码和它的输出:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-


from multiprocessing import Pool
from subprocess import check_output,CalledProcessError


def job(cmd):

    result = ""
    try:
        result = check_output(cmd.split())  # Split string into list.
        print("job result length = {0}".format(len(result)), file=sys.stdout)
    except CalledProcessError as error:
        raise Exception("Exit status of the child process: {0}\
            Command used to spawn child process: {1}\
            Output of the child process: {2}".format(error.returncode,error.cmd,error.output))


def main():

    # Sets up a process pool. Defaults to number of cores.
    # Each input gets passed to job and processed in a separate process.
    p = Pool()
    result = []
    try:
        # cmd_list is just a list of system commands which have been verified to work.
        result = list(p.imap_unordered(job, cmd_list))
        print("main result length = {0}".format(len(result)), file=sys.stdout)
        print("{0}".format(result), file=sys.stdout)
    except Exception as error:
        print("Error: {0}. Aborting...".format(error), file=sys.stderr)
        p.close()
        p.terminate()
    else:
        p.close()
        p.join()


if __name__ == '__main__':
    main()

输出

除了check_output执行的每个命令的输出之外,我的print语句显示了一些意想不到的结果:

job result length = 0
job result length = 0
main result length = 2
[None, None]

我希望作业结果长度等于2,结果包含子进程的返回值。

1 个答案:

答案 0 :(得分:1)

result是一个局部变量。要么退还它:

def job(cmd):
    # something goes here
    return result

或者让它成为全球性的:

result = ""
def job(cmd):
    global result
    # something goes here
    result = whatever it shall be.

或参数化:

def job(cmd, result):
    result = whatever it shall be.