我正在尝试运行多个实验,它们位于不同的文件夹中。我想将结果保存在主文件夹中。像这样:
主文件夹
我已经尝试使用以下代码:
multipledefine
但是,这仅运行第一个Run_file,而不运行第二个。有人可以帮我吗?
答案 0 :(得分:0)
第二个import Run_file
被忽略,因为python认为此模块已导入。
要么用以下语句替换这些导入语句:import Experiment_1.Run_file
,而不必忘记在子目录中添加__init__.py
文件,
或者您可以像从命令行中那样使用subprocess调用python脚本;
from subprocess import call
call(["python", "./path/to/script.py"])
您还缺少有关当前目录的要点:
mydir = os.getcwd() # would be the MAIN folder
中,mydir
仍然是前一个子文件夹答案 1 :(得分:0)
尝试子流程:
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);
答案 2 :(得分:0)
如果您的目标是在任何子文件夹中运行所有名为Run_fily.py
的脚本,那么当从主文件夹中的Main_run_file.py
开始时,如下所示的python Main_run_file.py
将完成此任务。
from pathlib import Path
from subprocess import run
for script in Path.cwd().rglob('Run_file.py'):
run(f'python {script.name}', cwd=script.parent)
如果仅通过不更改当前工作目录(cwd
)就可以实现“将结果保存在主文件夹中”,那么subprocess.run
的调用就是这样:
run(f'python {script}')