Python subprocess.Popen() 等待完成

2022-01-18 00:00:00 python subprocess popen

问题描述

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

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

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

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.

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

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

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 Log2timeline from 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.

最好的方法是什么?

谢谢!


解决方案

使用Popen.等待:

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

或 check_output, check_call 等待返回码取决于你想要做什么和python的版本.

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

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

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

您也可以使用 call 但如果您有,则不会引发任何错误可能需要也可能不需要的非零返回码

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

相关文章