【问题标题】:Running multiple Python scripts in different directories in a sequence依次在不同目录中运行多个 Python 脚本
【发布时间】:2019-06-21 10:12:12
【问题描述】:

我正在尝试运行多个实验,它们位于不同的文件夹中。我想将结果保存在主文件夹中。像这样的:

主文件夹

  • Main_run_file.py
    • Results.txt
    • 实验_1
      • Run_file.py
    • 实验_2
      • Run_file.py
    • 实验_3
      • Run_file.py

我已经尝试过以下代码:

import os

mydir = os.getcwd() # would be the MAIN folder
mydir_tmp = mydir + "\Experiment_1 - 40kmh" # add the first experiment folder name
mydir_new = os.chdir(mydir_tmp) # change the current working directory
mydir = os.getcwd() # set the main directory again
import Run_file

mydir = os.getcwd() # would be the MAIN folder
mydir_tmp = mydir + "/Experiment_1 - 60kmh" # add the second experiment folder name
mydir_new = os.chdir(mydir_tmp) # change the current working directory
mydir = os.getcwd() # set the main directory again
import Run_file

但是,这只运行第一个 Run_file 而不是第二个。有人可以帮我解决这个问题吗?

【问题讨论】:

标签: python-3.x


【解决方案1】:

第二个import Run_file 被忽略,因为python 认为这个模块已经被导入了。

您可以将这些导入语句替换为如下语句:import Experiment_1.Run_file,同时不要忘记在子目录中添加 __init__.py 文件,

或者您使用subprocess 调用您的python 脚本,就像您在命令行中所做的那样;

from subprocess import call

call(["python", "./path/to/script.py"])

您也错过了有关当前目录的要点:

  1. 在第二个mydir = os.getcwd() # would be the MAIN folder中,mydir仍然是前一个子文件夹
  2. Python 导入系统不关心您是否更改工作目录:使用取决于您的 python 安装和运行主脚本的目录的 python 路径管理导入。

更多:https://docs.python.org/3/reference/import.html

【讨论】:

    【解决方案2】:

    尝试子流程:

    import subprocess
    
    with open("Results.txt", "w+") as output:
        subprocess.call(["python", "./Experiment_1/Run_file.py"], stdout=output);
        subprocess.call(["python", "./Experiment_2/Run_file.py"], stdout=output);
        ...
    

    如果您需要将参数传递给您的Run_file.py,只需添加即可:

    subprocess.call(["python", "./Experiment_2/Run_file.py arg1"], stdout=output);
    

    【讨论】:

      猜你喜欢
      • 2017-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-27
      相关资源
      最近更新 更多