[英]How to raise an Exception using the stderr, stdout info of Popen in Python?
我有一個可配置的腳本,它的某些部分在 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.