Python使用subprocess执行ls命令无法捕获输出存入变量如何解决
问题原因
你遇到的空输出问题是两个常见的subprocess使用错误共同导致的:
- 通配符
*未被正确展开:subprocess.Popen默认不启用shell解析,你直接把带*的路径放在参数列表里时,ls命令会把/sys/class/net/e*/device/virtfn*当成字面量文件名查找,找不到对应文件自然返回空结果。 - 未指定标准输出捕获:你创建
Popen对象时没有添加stdout=subprocess.PIPE参数,默认情况下命令输出会直接打印到当前终端,communicate()方法无法捕获到输出内容。
解决方案
这里提供两种可行的实现方式:
方案1:使用glob预展开路径(推荐,无安全风险)
不需要启用shell,通过Python标准库glob预先完成通配符路径展开,避免shell注入隐患,适配所有场景:
import subprocess import glob def getMacOfBusSlotFunction(self, slotbus, slotslot, slotfunction): # 预展开所有匹配通配符的路径 match_paths = glob.glob("/sys/class/net/e*/device/virtfn*") myParentDevicesProcess = subprocess.Popen( ["ls", "-l"] + match_paths, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True # Python3.7+支持,直接返回字符串无需手动decode ) stdout, stderr = myParentDevicesProcess.communicate() # 如需排查错误可打印stderr内容 # print(stderr) print(stdout)
方案2:启用shell解析
适合快速调试场景,注意如果命令参数包含用户输入,存在shell注入风险:
import subprocess def getMacOfBusSlotFunction(self, slotbus, slotslot, slotfunction): myParentDevicesProcess = subprocess.Popen( "ls -l /sys/class/net/e*/device/virtfn*", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ) stdout, stderr = myParentDevicesProcess.communicate() print(stdout)
内容的提问来源于stack exchange,提问作者Ruth Edges
相关产品推荐
相关产品推荐

