我知道這個問題已經在這裏回答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