所以我想從os.popen搬往subprocess.popen所推薦的用戶指南。我遇到的唯一困難是我似乎無法找到使readlines()工作的方法。Python子進程readlines()?
所以我曾經是能夠做到
list = os.popen('ls -l').readlines()
但我不能做
list = subprocess.Popen(['ls','-l']).readlines()
所以我想從os.popen搬往subprocess.popen所推薦的用戶指南。我遇到的唯一困難是我似乎無法找到使readlines()工作的方法。Python子進程readlines()?
所以我曾經是能夠做到
list = os.popen('ls -l').readlines()
但我不能做
list = subprocess.Popen(['ls','-l']).readlines()
隨着subprocess.Popen
,使用communicate
來讀取和寫入數據:
out, err = subprocess.Popen(['ls','-l'], stdout=subprocess.PIPE).communicate()
然後,您總是可以將流程'stdout
中的字符串與分開。
out = out.splitlines()
認爲這是意味着是「漂亮的新途徑「這樣做。感謝您的回答,我會在超時時間到時將其設置。我迷惑不解。 – jdborg
用'communicate'的問題是,你的所有輸出的同時,以非遞歸'ls'的情況下是不太可能有問題。通過使用'stdout'成員,你可以逐行閱讀(想想'find')。 –
ls = subprocess.Popen(['ls','-l'], stdout=subprocess.PIPE)
out = ls.stdout.readlines()
,或者,如果你想讀行由行(也許是其他過程比ls
更密集):
for ln in ls.stdout:
# whatever
這種方法比公認的答案更可取,因爲它允許在子過程產生輸出時通讀輸出。 – Hoons
Making a system call that returns the stdout output as a string:
lines = subprocess.check_output(['ls', '-l']).splitlines()
使用子的更詳細的方式。
# 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()
寧願做'名單= subprocess.call([ 'ls' 的, ' - L'])readlines方法() ' – jdborg
這是不對的 - 'call'只返回返回代碼,而不是輸出。 – agf
http://stackoverflow.com/questions/2924310/whats-a-good-equivalent-to-pythons-subprocess-check-call-that-returns-the-conte – jfs