如何以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
相关产品推荐
相关产品推荐

