How to suppress or capture the output of subprocess.run()?

后端 未结 2 1621
春和景丽
春和景丽 2020-12-23 18:54

From the examples in docs on subprocess.run() it seems like there shouldn\'t be any output from

subprocess.run(["l         


        
相关标签:
2条回答
  • 2020-12-23 19:44

    ex: to capture the output of ls -a

    import subprocess
    ls = subprocess.run(['ls', '-a'], capture_output=True, text=True).stdout.strip("\n")
    print(ls)
    
    0 讨论(0)
  • 2020-12-23 19:47

    Here is how to suppress output, in order of decreasing levels of cleanliness. They assume you are on Python 3.

    1. You can redirect to the special subprocess.DEVNULL target.
    import subprocess
    
    subprocess.run(['ls', '-l'], stdout=subprocess.DEVNULL)
    # The above only redirects stdout...
    # this will also redirect stderr to /dev/null as well
    subprocess.run(['ls', '-l'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    # Alternatively, you can merge stderr and stdout streams and redirect
    # the one stream to /dev/null
    subprocess.run(['ls', '-l'], stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT)
    
    1. If you want a fully manual method, can redirect to /dev/null by opening the file handle yourself. Everything else would be identical to method #1.
    import os
    import subprocess
    
    with open(os.devnull, 'w') as devnull:
        subprocess.run(['ls', '-l'], stdout=devnull)
    

    Here is how to capture output (to use later or parse), in order of decreasing levels of cleanliness. They assume you are on Python 3.

    1. If you simply want to capture both STDOUT and STDERR independently, AND you are on Python >= 3.7, use capture_output=True.
    import subprocess
    
    result = subprocess.run(['ls', '-l'], capture_output=True)
    print(result.stdout)
    print(result.stderr)
    
    1. You can use subprocess.PIPE to capture STDOUT and STDERR independently. This does work on Python versions < 3.7, such as Python 3.6.
    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)
    

    NOTE: By default, captured output is returned as bytes. If you want to capture as text (e.g. str), use universal_newlines=True (or on Python >=3.7, use the infinitely more clear and easy-to-understand option text=True - it's the same a universal_newlines but with a different name).

    0 讨论(0)
提交回复
热议问题