2011-09-19 73 views
11

所以我想從os.popen搬往subprocess.popen所推薦的用戶指南。我遇到的唯一困難是我似乎無法找到使readlines()工作的方法。Python子進程readlines()?

所以我曾經是能夠做到

list = os.popen('ls -l').readlines() 

但我不能做

list = subprocess.Popen(['ls','-l']).readlines() 
+1

寧願做'名單= subprocess.call([ 'ls' 的, ' - L'])readlines方法() ' – jdborg

+2

這是不對的 - 'call'只返回返回代碼,而不是輸出。 – agf

+0

http://stackoverflow.com/questions/2924310/whats-a-good-equivalent-to-pythons-subprocess-check-call-that-returns-the-conte – jfs

回答

23

隨着subprocess.Popen,使用communicate來讀取和寫入數據:

out, err = subprocess.Popen(['ls','-l'], stdout=subprocess.PIPE).communicate() 

然後,您總是可以將流程'stdout中的字符串與分開。

out = out.splitlines() 
+0

認爲這是意味着是「漂亮的新途徑「這樣做。感謝您的回答,我會在超時時間到時將其設置。我迷惑不解。 – jdborg

+3

用'communicate'的問題是,你的所有輸出的同時,以非遞歸'ls'的情況下是不太可能有問題。通過使用'stdout'成員,你可以逐行閱讀(想想'find')。 –

25
ls = subprocess.Popen(['ls','-l'], stdout=subprocess.PIPE) 
out = ls.stdout.readlines() 

,或者,如果你想讀行由行(也許是其他過程比ls更密集):

for ln in ls.stdout: 
    # whatever 
+1

這種方法比公認的答案更可取,因爲它允許在子過程產生輸出時通讀輸出。 – Hoons

3
list = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE).communicate()[0].splitlines() 
help(subprocess)

+0

這不是線條列表,它是單個多行字符串。 – agf

+0

好點,固定 – Kimvais

8

Making a system call that returns the stdout output as a string

lines = subprocess.check_output(['ls', '-l']).splitlines() 
+0

不錯,我想這不是廣爲人知,因爲它僅是Python的2.7+。 – agf

+0

@agf:按照鏈接,適用於較老的Python版本。 – jfs

+0

我知道,我已經遵循你發佈的兩個鏈接(和upvoted每個職位)。我很驚訝,我不知道這個便利功能,直到我看到它是2.7+。 – agf

3

使用子的更詳細的方式。

 # Set the command 
     command = "ls -l" 

     # Setup the module object 
     proc = subprocess.Popen(command, 
          shell=True, 
          stdin=subprocess.PIPE, 
          stdout=subprocess.PIPE, 
          stderr=subprocess.PIPE) 

     # Communicate the command 
     stdout_value,stderr_value = proc.communicate() 

     # Once you have a valid response, split the return output  
     if stdout_value: 
      stdout_value = stdout_value.split()