簡體   English   中英

Python 子進程 readlines()?

[英]Python subprocess readlines()?

所以我試圖按照用戶指南的建議從 os.popen 轉移到 subprocess.popen 。 我遇到的唯一麻煩是我似乎找不到使 readlines() 工作的方法。

所以我曾經能夠做到

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

但我做不到

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

或者,如果您想逐行閱讀(也許另一個過程比ls更密集):

for ln in ls.stdout:
    # whatever

使用subprocess.Popen ,使用communicate來讀寫數據:

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

然后,您始終可以使用splitlines()從進程的stdout拆分字符串。

out = out.splitlines()

進行系統調用,將 stdout 輸出作為字符串返回

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

直接從help(subprocess)

更詳細的使用子流程的方法。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM