Python subprocess.Popen() 等待完成

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28284715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:03:19  来源:igfitidea点击:

Python subprocess.Popen() wait for completion

pythonsubprocesspopen

提问by DJMcCarthy12

I am writing a small script to serially walk through a directory and run a command on the subdirectories therein.

我正在编写一个小脚本来连续遍历目录并在其中的子目录上运行命令。

I am running into a problem however with Popen()that it will walk through the directories and run the desired command without waiting for the previous one to finish. i.e.

但是,我在使用Popen()时遇到了一个问题,它将遍历目录并运行所需的命令,而无需等待前一个命令完成。IE

for dir in dirs:
    #run command on the directory here.

it kicks off the command for each dir without caring about it afterwards. I want it to wait for the current one to finish, then kick off the next. The tool I am using on the directories is Log2timelinefrom SANS SIFT which takes quite a while and produces quite a bit of output. I don't care about the output, I just want the program to wait before kicking off the next.

它为每个目录启动命令,之后不关心它。我希望它等待当前一个完成,然后开始下一个。我在目录上使用的工具Log2timeline来自 SANS SIFT,它需要很长时间并产生相当多的输出。我不在乎输出,我只希望程序在开始下一个之前等待。

What's the best way to accomplish this?

实现这一目标的最佳方法是什么?

Thank you!

谢谢!

采纳答案by Padraic Cunningham

Use Popen.wait:

使用Popen.wait

process = subprocess.Popen(["your_cmd"]...)
process.wait()

Or check_output, check_callwhich all wait for the return code depending on what you want to do and the version of python.

或者 check_outputcheck_call,它们都等待返回代码,具体取决于您想要做什么和 python 版本。

If you are using python >= 2.7 and you don't care about the output just use check_call.

如果您使用的是 python >= 2.7 并且您不关心输出,请使用check_call.

You can also use callbut that will not raise any error if you have a non-zero return code which may or may not be desirable

您也可以使用call ,但如果您有一个非零的返回码,这可能会或可能不会出现任何错误,但不会引发任何错误

回答by Joran Beasley

subprocess.check_output( ... )

will block ... and can be used instead of Popen

将阻止......并且可以用来代替 Popen

however if you are set on Popen

但是,如果您设置为 Popen

subprocess.Popen(...).communicate() 

will also block until the process returns

也会阻塞直到进程返回