我有一个可配置的脚本,并且该脚本的某些部分可以在systemX上正常运行,而在systemY上却出现错误,因为该命令仅是SystemX知道的。
process = subprocess.Popen (cmd_false, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = process.communicate()
print "OUTPUT: ", output
print "ERROR: ", error
输出:
错误:500-找不到命令cmd_false
错误:
((这里未打印任何内容)
使用try-except-else机制,尽管遇到此错误在try块中,并期望代码跳入except块中,结束于else块。
顺便说一句,我使用了以下代码段,但它不会引发错误,因为它仅返回子进程的退出状态:
if(process.returncode != 0):
raise Exception()
脚本
#!/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')
输出
$ 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