Python中subprocess.check_output ping无效IP时无法返回结果如何解决
问题原因
subprocess.check_output 的默认行为是:仅当执行的命令退出状态码为0(即命令执行成功)时,才会返回标准输出内容;如果命令执行失败返回非0状态码(比如ping不通目标IP时ping命令就会返回非0退出码),会直接抛出CalledProcessError异常中断代码运行,因此你看不到返回结果,后续代码也无法执行。
另外你给出的示例代码存在语法问题:命令列表里的IP地址未加引号,不是合法的字符串类型,运行时会直接触发语法错误,需要修正为'1.1.1.1'、'0.0.0.0'这样的字符串格式。
解决方案
方案1:Python 3.7及以上版本(推荐)
给check_output添加check=False参数关闭退出码检查,同时添加stderr=subprocess.STDOUT把标准错误合并到输出中,即可无论ping成功失败都返回完整输出:
import subprocess command = ['ping', '-c', '1', '0.0.0.0'] # text=True可以直接返回字符串,无需手动decode output = subprocess.check_output( command, stderr=subprocess.STDOUT, text=True, encoding='utf-8', check=False ) print(output)
方案2:兼容低版本Python
通过捕获CalledProcessError异常,从异常对象的output属性中获取命令输出内容:
import subprocess command = ['ping', '-c', '1', '0.0.0.0'] try: output = subprocess.check_output( command, stderr=subprocess.STDOUT, text=True, encoding='utf-8' ) except subprocess.CalledProcessError as e: # 执行失败时从异常对象中获取输出 output = e.output print(output)
内容的提问来源于stack exchange,提问作者Skytlz
相关产品推荐
相关产品推荐

