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

如何以Pythonic方式从目标Python文件的所在目录运行该文件

解决方案

你可以直接用Python内置的subprocess模块实现,这种方式脚本运行环境互相隔离,不会互相影响,是最推荐的方案:

import subprocess
import os

# 获取test.py自身的绝对路径,逐级往上找项目根目录
test_py_abs_path = os.path.abspath(__file__)
one_dir_path = os.path.dirname(test_py_abs_path)
main_root_path = os.path.dirname(one_dir_path)
# 拼接得到other.py的所在目录和完整路径
other_py_dir = os.path.join(main_root_path, "two")
other_py_full_path = os.path.join(other_py_dir, "other.py")

# 运行other.py,cwd参数指定工作目录为other.py所在的two文件夹
subprocess.run(
    ["python", other_py_full_path],
    cwd=other_py_dir,
    check=True
)

参数说明

  • cwd:专门用来指定子进程运行时的工作目录,设置为main/two路径后,other.py运行时读写相对路径都会以这个目录为基准
  • check=True:other.py运行报错时会自动抛出异常,方便排查问题,不需要可以删掉
  • 如果你的环境Python启动命令是python3,把列表里的python替换成python3即可

备选方案(直接在当前进程运行other.py)

如果你不需要环境隔离,也可以切换当前进程的工作目录后直接执行other.py的代码:

import os
import sys

test_py_abs_path = os.path.abspath(__file__)
main_root_path = os.path.dirname(os.path.dirname(test_py_abs_path))
other_py_dir = os.path.join(main_root_path, "two")
other_py_full_path = os.path.join(other_py_dir, "other.py")

# 保存原有工作目录,执行完切回,避免影响后续代码
origin_cwd = os.getcwd()
try:
    os.chdir(other_py_dir)
    # 把two目录加到导包搜索路径,避免other.py导包报错
    sys.path.insert(0, other_py_dir)
    with open(other_py_full_path, "r", encoding="utf-8") as f:
        exec(f.read())
finally:
    os.chdir(origin_cwd)

注意:该方案会共享test.py的运行环境,可能出现变量冲突、导包异常等问题,非必要不推荐使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 21:45:07