【发布时间】:2016-03-07 23:21:59
【问题描述】:
我知道这个问题之前已经回答过Python popen command. Wait until the command is finished 但问题是我不明白答案以及如何将它应用到我的代码中,所以请不要在没有一点帮助的情况下将这个问题标记为之前提出的问题:)
我有一个函数,它接受一个 shell 命令并执行它并返回变量输出。
它工作正常,只是我不希望控制流继续直到过程完全完成。这样做的原因是我正在使用 imagemagick 命令行工具创建图像,当我尝试访问它们以获取信息时不久,它们是不完整的。这是我的代码..
def send_to_imagemagick(self, shell_command):
try:
# log.info('Shell command = {0}'.format(shell_command))
description=os.popen(shell_command)
# log.info('description = {0}'.format(description))
except Exception as e:
log.info('Error with Img cmd tool {0}'.format(e))
while True:
line = description.readline()
if not line: break
return line
非常感谢@Ruben 这是我用来完成它的,所以它可以正确返回输出。
def send_to_imagemagick(self, shell_command):
args = shell_command.split(' ')
try:
description=Popen(args, stdout=subprocess.PIPE)
out, err = description.communicate()
return out
except Exception as e:
log.info('Error with Img cmd tool {0}'.format(e))
【问题讨论】:
-
为什么使用
os.popen而不是subprocess.popen?子进程替换 os.popen。我认为你想这样做:description.communicate()等到它完成。见docs.python.org/2/library/… -
那我该怎么写呢?像这样 ...description= subprocess.call([shell_command])
-
return line将打破while循环,因为该函数将退出,我认为您应该在这里使用yield line而不是return。
标签: python subprocess popen imagemagick-convert