Python os.popen:如何确保popen(...)在继续之前完成执行?

时间:2014-01-28 19:06:32

标签: python multithreading popen

我有以下代码:

pwd = '/home/user/svnexport/Repo/'

updateSVN = "svn up " + pwd
cmd = os.popen(updateSVN)

getAllInfo = "svn info " + pwd + "branches/* " + pwd + "tags/* " + pwd + "trunk/*"
cmd = os.popen(getAllInfo)

cmd = os.popen(updateSVN)开始执行之前,我如何确定cmd = os.popen(getAllInfo)已完成执行?

4 个答案:

答案 0 :(得分:2)

您应该使用subprocess

import subprocess
import glob
pwd = '/home/user/svnexport/Repo/'

updateSVN = ["svn", "up", pwd]
cmd = subprocess.Popen(updateSVN)
status = cmd.wait()

# the same can be achieved in a shorter way:
filelists = [glob.glob(pwd + i + "/*") for i in ('branches', 'tags', 'trunk')]
filelist = sum(filelists, []) # add them together

getAllInfo = ["svn", "info"] + filelist
status = subprocess.call(getAllInfo)

如果您需要捕获子流程的输出,请执行

process = subprocess.Popen(..., stdout=subprocess.PIPE)
data = process.stdout.read()
status = subprocess.wait()

答案 1 :(得分:1)

如果您需要终止第一个命令,则不需要多线程。你可以做到

os.system(updateSVN)
os.system(getAllInfo)

如果您真的想使用updateSVN,可以通过

等待它
for _ in cmd:
    pass

答案 2 :(得分:1)

尝试使用wait()方法:

pwd = '/home/user/svnexport/Repo/'

updateSVN = "svn up " + pwd
cmd = os.popen(updateSVN)
cmd.wait()

getAllInfo = "svn info " + pwd + "branches/* " + pwd + "tags/* " + pwd + "trunk/*"
cmd = os.popen(getAllInfo)

答案 3 :(得分:1)

如果您想等待,最简单的方法是使用以下子进程函数之一

  • 致电
  • check_call
  • check_output

只有在shell中的命令执行完成后,才会返回其中的每一个,请参阅docs for details