gpt4 book ai didi

python - subprocess.check_output() 有问题

转载 作者:行者123 更新时间:2023-11-28 16:36:34 29 4
gpt4 key购买 nike

我在使用 subprocess.check_output() 时遇到了一些奇怪的问题。起初我只是使用 subprocess.call() 并且一切正常。然而,当我简单地将 call() 切换为 check_output() 时,我收到了一个奇怪的错误。

在代码之前(工作正常):

def execute(hosts):
''' Using psexec, execute the batch script on the list of hosts '''
successes = []
wd = r'c:\\'
file = r'c:\\script.exe'
for host in hosts:
res = subprocess.call(shlex.split(r'psexec \\\\%s -e -s -d -w %s %s' % (host,wd,file)))
if res.... # Want to check the output here
successes.append(host)
return successes

代码后(不起作用):

def execute(hosts):
''' Using psexec, execute the batch script on the list of hosts '''
successes = []
wd = r'c:\\'
file = r'c:\\script.exe'
for host in hosts:
res = subprocess.check_output(shlex.split(r'psexec \\\\%s -e -s -d -w %s %s' % (host,wd,file)))
if res.... # Want to check the output here
successes.append(host)
return successes

这给出了错误: Error

我无法重定向它,因为程序卡在这里,我无法按 ctrl-c 退出。任何想法为什么会这样?可能导致此问题的 subprocess.call() 和 check_output() 之间有什么区别?

这是包含多处理部分的附加代码:

PROCESSES = 2
host_sublists_execute = [.... list of hosts ... ]
poolE = multiprocessing.Pool(processes=PROCESSES)
success_executions = poolE.map(execute,host_sublists_execute)
success_executions = [entry for sub in success_executions for entry in sub]
poolE.close()
poolE.join()

谢谢!

最佳答案

您遇到的是Python Issue 9400 .

关于 subprocess.call()subprocess.check_output(),您必须了解一个关键区别。 subprocess.call() 将执行您给它的命令,然后为您提供返回代码。另一方面,subprocess.check_output() 将程序的输出以字符串的形式返回给您,但它会尽力帮您检查程序的返回码,会引发异常 (subprocess.CalledProcessError) 如果程序没有成功执行(返回非零返回代码)。

当您使用多处理池调用 pool.map() 时,它会尝试将子进程中的异常传播回主进程并在那里引发异常。显然 subprocess.CalledProcessError 异常类的定义方式存在问题,因此当多处理库尝试将异常传播回 main 时酸洗失败。

您正在调用的程序正在返回一个非零返回码,这使得 subprocess.check_output() 引发异常,并且 pool.map() 可以无法正确处理它,因此您会得到 TypeError,这是由于尝试检索异常失败而导致的。

作为旁注,subprocess.CalledProcessError 的定义一定是一团糟,因为如果我打开我的 2.7.6 终端,导入子进程,然后手动引发错误,我仍然会得到TypeError,所以我认为这不仅仅是一个 pickling 问题。

关于python - subprocess.check_output() 有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25435866/

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