To catch errors with subprocess.check_output()
, you can use CalledProcessError
. If you want to use the output as string, decode it from the bytecode.
# \return String of the output, stripped from whitespace at right side; or None on failure.
def runls():
import subprocess
try:
byteOutput = subprocess.check_output(['ls', '-a'], timeout=2)
return byteOutput.decode('UTF-8').rstrip()
except subprocess.CalledProcessError as e:
print("Error in ls -a:\n", e.output)
return None