繁体   English   中英

如何在 Python 中使用 Popen 的 stderr、stdout 信息引发异常?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM