2014-01-28 99 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

相關問題