在其他文件夹中运行另一个Python脚本

时间:2018-09-30 10:30:18

标签: 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])

1 个答案:

答案 0 :(得分:1)

  

有多种方法。我将按倒序排列   偏好(,最好的第一,最差的最后):

     
      
  1. 像对待模块一样对待它: import file。这是好的,因为它是安全,快速和可维护的。代码按预期被重用   要做。大多数Python库使用扩展的多种方法运行   大量文件。强烈推荐。请注意,如果您的文件是   称为file.py,您的import应该包括.py   扩展名结尾。
  2.   
  3. 臭名昭著(且不安全)的exec命令: execfile('file.py')。不安全,hacky,通常是错误的答案。   尽可能避免。
  4.   
  5. 产生一个shell进程: os.system('python file.py')。绝望时使用。
  6.   
     

来源:How can I make one python file run another?


解决方案

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