我知道这个问题已经在这里回答Python popen command. Wait until the command is finished 但事情是我不明白答案,我怎么可以将它应用于我的代码,所以请不要将此问题标记为被问到之前没有一点帮助,请:))Python popen shell命令等到子进程完成
我有一个函数,它接受一个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()'等到它完成。 请参阅https://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate – Noxeus
那么我该如何编写它?像这样... description = subprocess.call([shell_command]) – whoopididoo
查看我的回答.. – Noxeus