如何并行运行多个命令并获取其输出(通过/失败)?

时间:2018-07-17 01:08:47

标签: python subprocess python-multiprocessing

我正在尝试并行运行3个打印命令并获取所有这三个命令的输出,以便我可以确定其通过还是失败?当前输出为StopIteration,正如我期望的打印命令输出一样,我在哪里出错?

['', '', '']

输出:-

from multiprocessing import Pool
from multiprocessing.dummy import Pool as ThreadPool 
from subprocess import Popen, PIPE, call


cmds = ["print username1","print username2 ","print username3"]
def function_create_cmds(cmd):
    proc = Popen(cmd , shell=True, stdout=PIPE, stderr=PIPE)
    (output, error) = proc.communicate()
    return output

# Make the Pool of workers
pool = ThreadPool(3) 
results = pool.map(function_create_cmds, cmds)
#close the pool and wait for the work to finish 
pool.close() 
pool.join() 
print results

1 个答案:

答案 0 :(得分:1)

您的代码没有任何问题。如果您正确设置了打印机,则print命令通常没有输出(假设此命令在Windows中运行)。

将所有print命令替换为echo,您将看到以下输出:

[b'username1\r\n', b'username2 \r\n', b'username3\r\n']

如果您希望从print命令中捕获任何错误,可以使用以下命令将标准错误重定向到标准输出:

proc = Popen(cmd , shell=True, stdout=PIPE, stderr=subprocess.STDOUT)