[英]How to raise an Exception using the stderr, stdout info of Popen in Python?
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.我有一个可配置的脚本,它的某些部分在 systemX 上正常运行,同时在 systemY 上出现错误,因为该命令只有 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
错误:500 - 找不到命令 cmd_false
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.使用 try-except-else 机制,尽管在 try 块中遇到此错误并期望代码跳转到 except 块,但它最终在 else 块中。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.