2015-12-20 22 views
2

我想檢索一些關於我的perforce客戶端使用python腳本的信息。我只希望獲取相關服務器的地址信息,cleint根等如下:如何從一個子進程命令獲取輸出作爲Python中的列表?

ping_string = subprocess.Popen(['p4', 'info','ls'], stdout=subprocess.PIPE).communicate()[0] 
print ping_string 

,所以我得到輸出:

User name: hello 
Client name: My_machine 
Client host: XYZ 
Current directory: c:\ 
Peer address: 1.2... 
Client address: 1.102.... 
Server address: abcd 
Server root: D:\scc\data 

但正如我想要檢索服務器地址,客戶端地址等所以,爲此,我希望輸出爲列表的形式。所以,請建議如何以列表類型的形式獲得輸出。

回答

2

使用check_output簡化得到命令的輸出,所以你可以這樣做:

out = subprocess.check_output(cmd) 

lines = out.splitlines() 

注意,每一行都將包含尾隨換行字符。

或者,如果你在冒號後所需的數據:

lines = [l.split(':', 1)[1].strip() for l in out.splitlines() 
     if ':' in l] 

l.split(':', 1)[1]走的是無論是冒號後面。 .strip()刪除周圍的空格。 if ':' in l是針對不包含冒號的行的保護。

相關問題