2014-01-28 61 views
0

我有以下代码:Python os.popen:如何确保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)开始执行之前?

+3

你应该使用'subprocess.call()'代替。 – chepner

+0

Seconding chepner的评论 - subprocess.call(或subprocess.check_call)是正确的方式来做到这一点。 – babbageclunk

回答

1

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

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

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

for _ in cmd: 
    pass 
+0

请不要暗示'os.system()',因为有更好的方法。 – glglgl

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) 
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

如果你要等待,最简单的方法是使用下面的子的一个功能

  • 呼叫
  • check_call
  • check_output

那些回报每一个仅在后壳命令执行完成,看到docs for details

相关问题