1

**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)?

3
  • Only you can know which encoding to use for your snmpwalk program. encoding="utf-8" is a safe choice for UNIX programs, in general. Commented Mar 7, 2022 at 14:02
  • encoding=encodings.utf_8 doesn't work @AKX Commented Mar 7, 2022 at 14:53
  • encoding="utf-8". Commented Mar 7, 2022 at 15:39

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

6 Comments

It does, if you use stdout=subprocess.PIPE and then read the return object's stdout. Read the doc
It's your responsibility to tell subprocess.run which encoding to use, or to know how to decode it once you get the raw byte stream from the subprocess. You can use text=True and see if the default encoding works for you, though.
Use the encoding argument if UTF-8 isn't already the default. Please see the documentation for subprocess.run.
@chepner encoding=encodings.utf_8 doesn't work
@Dan "Doesn't work" will help people understand what the problem is. You must explain exactly what doesn't work. And why are you doing encoding=encodings.utf_8? Nobody told you to do that. They explicitly wrote encoding="utf-8".
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.