简体   繁体   中英

How to use subprocess without Try-Catch?

**Can someone answer my question under the only answer? **

I want to use subprocess and be able to read its output, so I used:

subprocess.check_output

But this wasn't enough for me, I wanted to hide writing to stderror so I added:

stderr=subprocess.DEVNULL

Which wasn't helpful as some commands now have the following output:

raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '['snmpwalk', '-t', '1', '-r', '1', '-v', '3', '-c', 'public', '31.208.215.122', '1.3.6.1.2.1.1.2.0']' returned non-zero exit status 1.

How can I fix this without try-catch (I don't want to harm performance as I am calling this code thousands of times)?

subprocess.run is your friend

subprocess.check_output will raise Exception upon failure. .run won't (unless given check=True )

Try something like:

In [1]: import subprocess

In [2]: proc = subprocess.run("echo bla", shell=True, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)

In [3]: print(proc.stdout.decode())
bla

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