在不同的文件夹中运行另一个 Python 脚本

Avi*_*vic 5 python

如何在不同的文件夹中运行另一个 python 脚本?

我有主程序: calculation_control.py

在文件夹中calculation_folder,有calculation.py

我如何calculation_folder/calculation.py从内部运行calculation_control.py

到目前为止,我已经尝试了以下代码:

calculation_file = folder_path + "calculation.py"
if not os.path.isfile(parser_file) :

    continue


subprocess.Popen([sys.executable, parser_file])
Run Code Online (Sandbox Code Playgroud)

Mat*_*ith 9

有不止几种方法。我将按照倒置偏好的顺序列出它们(,最好的在前,最后是最差的):

  1. 把它当作一个模块来对待: import file . 这很好,因为它安全、快速且可维护。代码被重用,因为它应该完成。大多数 Python 库使用跨越大量文件的多种方法运行。强烈推荐。请注意,如果你的文件被调用file.py,您import应该包括.py 在最后延伸。
  2. 臭名昭著(且不安全)的exec命令: execfile('file.py') . 不安全,老套,通常是错误的答案。尽可能避免。
  3. 生成一个 shell 进程: os.system('python file.py') . 绝望时使用。

来源:如何让一个 python 文件运行另一个?


解决方案

Python 只在当前目录中搜索要导入的文件。但是,您可以通过将以下代码片段添加到calculation_control.py...

import sys
sys.path.insert(0, 'calculation_folder') # Note: if this relavtive path doesn't work or produces errors try replacing it with an absolute path
import calculation
Run Code Online (Sandbox Code Playgroud)