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

Python调用subprocess运行shell脚本时提示找不到.sh文件如何解决

Shell脚本找不到问题排查与解决方法

排查步骤

  • 验证Python运行时的工作目录是否和displaySoftware.sh存放目录一致
    可以在Python代码开头添加以下代码打印当前工作目录:
    import os
    print(os.getcwd())
    
    输出的路径即为Python的工作目录,确认.sh文件是否在该路径下。
  • 检查文件名拼写是否完全匹配,Linux/macOS环境下文件名大小写敏感,displaySoftware.sh和DisplaySoftware.sh会被识别为不同文件。
  • 检查.sh文件是否具备可执行权限,在终端对应目录下执行ls -l displaySoftware.sh即可查看权限,没有可执行权限时执行以下命令添加:
    chmod +x displaySoftware.sh
    

解决方法

  • 方法1:直接写.sh文件的绝对路径,示例如下:
    import subprocess
    # 替换为你实际的.sh文件完整绝对路径
    shellscript = subprocess.Popen(["/Users/xxx/scripts/displaySoftware.sh"], stdin=subprocess.PIPE)
    
    shellscript.stdin.write(b"yes\n") # Python3需传入bytes类型,加前缀b即可
    shellscript.stdin.close()
    returncode = shellscript.wait()
    
  • 方法2:通过cwd参数指定.sh文件所在的工作目录,示例如下:
    import subprocess
    # cwd参数填.sh文件所在的目录路径
    shellscript = subprocess.Popen(["./displaySoftware.sh"], stdin=subprocess.PIPE, cwd="/Users/xxx/scripts/")
    
    shellscript.stdin.write(b"yes\n")
    shellscript.stdin.close()
    returncode = shellscript.wait()
    
  • 方法3:如果.sh文件和Python脚本在同一目录,调用时添加./前缀即可,避免系统到PATH环境变量中搜索对应文件:
    shellscript = subprocess.Popen(["./displaySoftware.sh"], stdin=subprocess.PIPE)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:15:00