python-subprocess.check_output()有问题

我在使用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

这给出了错误:

我无法重定向它,因为程序挂在这里,我无法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()时,它将尝试将子流程中的异常传播回main并在其中引发异常.显然,subprocess.CalledProcessError异常类的定义方式存在问题,因此当多处理库尝试将异常传播回main时,酸洗失败.

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

附带说明一下,必须确实搞砸subprocess.CalledProcessError的定义,因为如果我打开2.7.6终端,导入子进程,然后手动引发错误,我仍然会收到TypeError,所以我不认为它仅仅是酸洗问题.

上一篇:python-Gunicorn子流程引发异常[Errno 10]


下一篇:Python可执行文件到Linux列出具有大小的文件