2016-12-15 75 views
2

從上subprocess.run()在文檔的例子,好像不應該有來自如何抑制subprocess.run()的輸出?

subprocess.run(["ls", "-l"]) # doesn't capture output 

但是任何輸出,當我嘗試在Python殼上市被打印出來。我想知道這是否是默認行爲,以及如何抑制run()的輸出。

+2

http://stackoverflow.com/questions/8529390/is-there-a-quiet-version-of-subprocess-call – user2290362

+1

'subprocess.run()'默認不捕獲stdout或stderr,要做所以需要爲'stdout'和/或'stderr'參數傳遞'PIPE'(它在鏈接文檔中是正確的)。所以,除非你這樣做,否則他們將像往常一樣從其他過程展示。 – martineau

+1

你想抑制輸出還是捕捉它? – SethMMorton

回答

8

抑制輸出,你可以,如果你想捕獲輸出(以供以後使用或分析)重定向到/dev/null

import os 
import subprocess 

with open(os.devnull, 'w') as devnull: 
    subprocess.run(['ls', '-l'], stdout=devnull) 
    # The above only redirects stdout... 
    # this will also redirect stderr to /dev/null as well 
    subprocess.run(['ls', '-l'], stdout=devnull, stderr=devnull) 
    # Alternatively, you can merge stderr and stdout streams and redirect 
    # the one stream to /dev/null 
    subprocess.run(['ls', '-l'], stdout=devnull, stderr=subprocess.STDOUT) 

,你需要使用subprocess.PIPE

import subprocess 
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE) 
print(result.stdout) 

# To also capture stderr... 
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
print(result.stdout) 
print(result.stderr) 

# To mix stdout and stderr into a single string 
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 
print(result.stdout) 
+4

請注意,從Python版本。 3.3實際上有一個'subprocess.DEVNULL',所以'stdout'參數可以在不使用'open'的情況下直接分配,只需使用'stdout = subprocess.DEVNULL'。 – EquipDev