Python subprocess.Popen() 等待完成

Python subprocess.Popen() wait for completion(Python subprocess.Popen() 等待完成)
本文介绍了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

这篇关于Python subprocess.Popen() 等待完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)