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

如何在Python中使用subprocess.run执行cat << EOF重定向写入操作

错误原因

你的现有写法存在两个核心问题:

  • << EOF 属于Shell专属的Here Document语法,subprocess.run 默认不启动Shell解释器,会将这类语法字符串直接当成cat的文件名参数处理,无法正常执行
  • 路径中的~是Shell提供的家目录展开语法,非Shell模式下不会自动解析为实际的用户家目录路径
正确实现方案

方案1(最推荐):直接使用Python原生文件操作实现

完全不需要调用外部cat命令,无额外依赖,性能和安全性最高:

import os

# 手动展开家目录路径
config_path = os.path.expanduser("~/.aws/config")
config_content = """[profile default]
key=value
"""

with open(config_path, "w", encoding="utf-8") as f:
    f.write(config_content)

方案2:通过subprocess启动Shell执行

如果必须复用现有Shell命令逻辑,可以开启shell=True参数直接传入完整Shell命令:

import subprocess

shell_cmd = """cat << EOF > ~/.aws/config
[profile default]
key=value
EOF
"""
# check=True会在命令执行失败时抛出异常,方便排查问题
subprocess.run(shell_cmd, shell=True, check=True)

注意:shell=True 存在命令注入安全风险,如果命令内容包含不可信的用户输入,禁止使用该方案

方案3:不启动Shell,通过stdin传递内容给cat

如果不想开启shell=True,也可以手动把文件内容传给cat的标准输入,同时手动展开路径:

import subprocess
import os

config_path = os.path.expanduser("~/.aws/config")
config_content = """[profile default]
key=value
"""

with open(config_path, "w", encoding="utf-8") as f:
    subprocess.run(
        ["cat"],
        input=config_content.encode("utf-8"),
        stdout=f,
        check=True
    )

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 09:24:09