我知道此问题已在此处得到解答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))
答案 0 :(得分:3)
使用subprocess.popen
:
该模块旨在替换几个较旧的模块和功能。
所以在你的情况下import subprocess
然后使用popen.communicate()
等待命令完成。
有关此文档,请参阅:here
所以:
from subprocess import Popen
def send_to_imagemagick(self, shell_command):
try:
# log.info('Shell command = {0}'.format(shell_command))
description=Popen(shell_command)
description.communicate()
# 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