subprocess.check_output() 出现问题

DJM*_*y12 3 python subprocess

我在使用时遇到一些奇怪的问题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
Run Code Online (Sandbox Code Playgroud)

代码之后(不起作用):

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
Run Code Online (Sandbox Code Playgroud)

这给出了错误: 错误

我无法重定向它,因为程序挂在这里,我无法按 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()
Run Code Online (Sandbox Code Playgroud)

谢谢!

skr*_*sme 5

您遇到了Python Issue 9400。

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

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

您调用的程序返回一个非零返回代码,这会subprocess.check_output()引发异常,并且pool.map()无法正确处理它,因此您会得到TypeError检索异常失败尝试的结果。

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