Python使用subprocess运行shell脚本无输出及报错问题如何解决?
问题根因
shell=True与参数列表混用错误:启用shell=True参数时,subprocess仅会将传入列表的第一个元素交给系统shell解析,剩余元素会被识别为shell本身的参数,而非脚本执行参数。Windows环境下会触发路径解析错误,km不是内部或外部命令就是系统将路径首位的km目录识别为待执行命令导致的。- 相对路径有效性校验缺失:使用的
km/example/example1/source/test.sh是相对路径,需要和Python脚本运行时的工作目录匹配才能正常定位到脚本。 - 脚本执行权限不足:Linux/macOS环境下需要给.sh脚本添加可执行权限,Windows环境需要确保系统已经安装了能解析.sh脚本的程序(如Git Bash、WSL)。
- 错误输出未打印:之前的代码未打印stderr的内容,无法感知脚本执行过程中抛出的路径错误、权限错误等异常。
解决方案
方案1:禁用shell=True(更安全,优先推荐)
shell=True会引入命令注入风险,非必要场景建议关闭,直接传入脚本路径调用即可。添加text=True参数可以直接获取字符串格式的输出,无需手动解码bytes类型。
import subprocess import os # 转换为绝对路径避免相对路径匹配错误 script_path = os.path.abspath("km/example/example1/source/test.sh") print("RUNNNING SHELL SCRIPT NOW") # Windows环境下可新增executable参数指定sh解析程序路径,例如 executable=r"C:\Program Files\Git\bin\sh.exe" proc = subprocess.Popen(script_path, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) out, err = proc.communicate() # 同时打印标准输出和错误信息,方便问题排查 print("标准输出:", out) print("标准错误:", err) print("SHELL SCRIPT RUN ENDED")
Linux/macOS环境下如果执行报错权限不足,运行命令chmod +x km/example/example1/source/test.sh给脚本添加可执行权限即可。
方案2:保留shell=True的正确写法
如果确实需要使用shell特性,不要传入列表格式的命令,直接传入字符串格式的执行命令即可:
import subprocess print("RUNNNING SHELL SCRIPT NOW") proc = subprocess.Popen("km/example/example1/source/test.sh", stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, text=True) out, err = proc.communicate() print("标准输出:", out) print("标准错误:", err) print("SHELL SCRIPT RUN ENDED")
快速排查技巧
- 先在系统终端直接执行脚本路径,确认脚本本身可以正常运行输出Hello World,再放到Python代码中调用。
- 始终打印stderr的输出内容,绝大多数执行异常都会在错误输出中明确提示原因。
内容的提问来源于stack exchange,提问作者eraisedtothepowerx
相关产品推荐
相关产品推荐

