gpt4 book ai didi

python - 捕获 check_output 值

转载 作者:太空宇宙 更新时间:2023-11-03 17:41:16 26 4
gpt4 key购买 nike

我试图捕获 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 执行的每个命令的输出之外,我的打印语句还显示了一些意想不到的结果:

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

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

最佳答案

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.

关于python - 捕获 check_output 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30516918/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com