简体   繁体   中英

Suppress stderr within subprocess.check_output()

I'm trying to find a way to ignore the stderr stream (something similar to 2> /dev/null ):

output = subprocess.check_output("netstat -nptl".split())

What should I add to the above command to achieve this?

Just tell subprocess to redirect it for you:

import os
import subprocess

with open(os.devnull, 'w') as devnull:
    output = subprocess.check_output(
        "netstat -nptl".split(), stderr=devnull
    )

Note that Python 3 adds a subprocess.DEVNULL object , saving you having to open this yourself:


import subprocess
    
output = subprocess.check_output(
    "netstat -nptl".split(), stderr=subprocess.DEVNULL
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM