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

在Jupyter中使用subprocess执行cd与pwd组合命令报错求助

解决subprocess执行cd .. && pwd时的"No such file or directory"错误

错误根源在于subprocess.run默认不会把传入的字符串当作shell命令解析——它会把整个(cd .. && pwd)当作一个可执行文件的路径去查找,自然找不到对应文件。

给你三种可行的解决方式:

  • 启用shell解析(适合复杂shell命令场景)
    通过添加shell=True参数让subprocess调用系统shell来解析命令字符串,同时加上参数捕获输出:

    import subprocess
    result = subprocess.run("(cd .. && pwd)", shell=True, capture_output=True, text=True)
    mypath = result.stdout.strip()
    

    capture_output=True用来捕获命令的输出内容,text=True让输出以字符串形式返回,strip()可以去掉结果末尾的换行符。

  • 用cwd参数指定工作目录(更安全,推荐)
    不需要依赖shell的cd命令,直接通过subprocess的cwd参数指定要执行命令的上级目录,再执行pwd:

    import subprocess
    result = subprocess.run("pwd", cwd="..", capture_output=True, text=True)
    mypath = result.stdout.strip()
    

    这种方式避免了shell注入的风险,也更符合subprocess的设计规范。

  • 直接用Python内置模块获取(最优解)
    其实完全不需要调用外部命令,用os模块就能直接获取上级目录的绝对路径,跨平台性更好:

    import os
    mypath = os.path.abspath(os.path.join(os.getcwd(), ".."))
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 19:55:19