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

Python subprocess调用bash脚本时sed的\u转义异常,无法修改脚本怎么办?

问题原因与解决方法

问题出在默认情况下,subprocess调用脚本时使用的是系统默认的/bin/sh而非bash,而POSIX标准的sh配套的sed不支持\u这种扩展语法,导致\u被当作普通字符输出成u前缀。

以下是两种可行的解决方式:

方式一:直接用bash执行脚本(推荐,避免shell注入风险)

修改subprocess的调用参数,明确指定用bash运行脚本,并将命令参数拆分传递:

val = subprocess.Popen(
    ['bash', f"{dir}/bash_script.sh", 'sk', '-s', variable, '-l', 'En'],
    cwd=working_dir
)

这种方式不需要启用shell=True,既保证了脚本在bash环境下执行,也避免了shell注入的安全问题。

方式二:指定shell为bash(保留shell=True的场景)

如果必须使用shell=True,可以通过executable参数指定使用bash作为解析shell:

val = subprocess.Popen(
    f"{dir}/bash_script.sh sk -s {variable} -l En",
    cwd=working_dir,
    shell=True,
    executable='/bin/bash'
)

这种方式会让bash来解析整个命令字符串,确保脚本内的sed命令能识别\u语法,将目录名首字母正确大写。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 05:05:18