I have a script which is configurable and some part of it functions on the systemX correctly while gives an error on the systemY because the command is only known to SystemX.
process = subprocess.Popen (cmd_false, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
print "OUTPUT: ", output
print "ERROR: ", error
OUTPUT:
error: 500 - command cmd_false not found
ERROR:
(Here is nothing printed)
Using a try-except-else mechanism, In spite of encountering this error in the try block and expecting the code to jump into except block, it end up in the else block.
Btw, I have used the following code snippet but it doesn't raise an error since it returns only the exit status of the child process:
if(process.returncode != 0):
raise Exception()
Script
#!/usr/bin/env python3
import subprocess, sys
def run_command(command: str):
try:
output = subprocess.check_output(command, shell=True, stderr=subprocess.STDOUT)
message = output.decode('utf-8')
print(f"SUCCESS: {message}")
except subprocess.CalledProcessError as err:
message = err.output.decode('utf-8')
print(f"ERROR: {message}")
#sys.exit(err.returncode)
except Exception as error:
print(f"ERROR: {error}")
print(f"ERROR: {command}")
#sys.exit(2)
run_command('ls -la dir_not_exist')
run_command('ls -la dir_exist')
Output
$ python3 test.py
ERROR: ls: cannot access 'dir_not_exist': No such file or directory
SUCCESS: total 8
drwxr-xr-x 2 user user 4096 Apr 26 11:20 .
drwxrwxr-x 3 user user 4096 Apr 26 11:20 ..
-rw-r--r-- 1 user user 0 Apr 26 11:20 test
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.