You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

不使用shell=True时subprocess.run执行cat读取Linux版本报错如何解决?

解决思路:不用shell=True执行cat读取/etc/*-release

首先得搞清楚为啥报错:当你不用shell=True时,subprocess.run不会让shell帮你解析通配符*,它会把/etc/*-release当成一个实实在在的文件名去查找,但系统里根本不存在这个名字的文件,所以就报"No such file or directory"了。

下面给你几个不用shell=True的可行方案:

方案1:用Python的glob模块手动展开通配符

Python自带的glob模块可以帮你解析文件路径的通配符,完全不需要依赖shell。你可以先用它找出所有匹配/etc/*-release的文件,再把这些文件作为cat命令的参数传进去:

import subprocess
import glob

try:
    # 先展开通配符,得到所有匹配的文件路径列表
    release_files = glob.glob('/etc/*-release')
    if not release_files:
        print("没有找到匹配的release文件")
    else:
        # 构造cat命令的参数列表:['cat', '/etc/os-release', '/etc/lsb-release', ...]
        cmd = ['cat'] + release_files
        result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
        # 处理执行结果
        if result.returncode == 0:
            print(result.stdout)
        else:
            print(f"执行失败:{result.stderr}")
except Exception as err:
    print(f"发生异常:{err}")

方案2:直接用Python读取文件,完全不用cat命令

既然安全要求很高,其实完全没必要调用外部的cat进程,Python自己就能搞定文件读取,更安全也更高效:

import glob

try:
    release_info = ""
    release_files = glob.glob('/etc/*-release')
    if not release_files:
        print("没有找到匹配的release文件")
    else:
        for file_path in release_files:
            with open(file_path, 'r') as f:
                release_info += f.read() + "\n"
        print(release_info)
except Exception as err:
    print(f"读取文件失败:{err}")

额外提示

  • 记得处理glob.glob返回空列表的情况,避免因为没有文件参数导致cat命令报错(比如某些极简Linux系统可能只有/etc/os-release,甚至可能没有这类文件)。
  • 用glob.glob时,它会自动处理通配符,和shell的解析逻辑基本一致,能覆盖绝大多数场景。

内容的提问来源于stack exchange,提问作者techhighlands

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:24:10