python-3.x 在传递命名空间时,将runfile替换为exec/subprocess.call

64jmpszr  于 2023-04-22  发布在  Python
关注(0)|答案(1)|浏览(104)

我有一个python脚本,它接受一个参数,比如test.py 1并生成一些数据。第二个脚本experiment.py重复启动test.py。我在Spyder IDE中使用runfile实现了这一点:
所以,experiment.py读起来像这样:

experiments = {}
for i in range(10):
    experiments[str(i)] = {}
    runfile(`test.py`, args=str(i), wdir=`/path/to/script/`, namespace=experiments[str(i)])

## some post-processing using data from the dict experiments

这允许我在单独的命名空间中为每个调用存储test.py的变量。一切都很好,但是(我的问题来了):

如何将runfile替换为execsubprocess.call,并能够传递命名空间和参数列表?

目标是从命令行而不是Spyder运行脚本。只是为了澄清,我知道执行此类任务的最佳方法是将test.py转换为函数。然而,我正试图用当前脚本test.py做,这是相当长的。

w8biq8rn

w8biq8rn1#

修改test.py以将其变量保存到文件中,然后在experiment.py中加载文件,而不是使用exec使用subprocess.run,以便您可以从命令行运行脚本,并避免使用特定于Spyder的runfile函数。
test.py看起来像这样

import sys
import json

arg = int(sys.argv[1])

# Your original code here

variables_to_save = {'variable1': variable1, 'variable2': variable2}
with open(f"variables_{arg}.json", "w") as f:
    json.dump(variables_to_save, f)

experiment.py

import subprocess
import json

experiments = {}
for i in range(10):
    experiments[str(i)] = {}
    
    subprocess.run(["python", "test.py", str(i)], cwd="/path/to/script/")
    
    with open(f"variables_{i}.json", "r") as f:
        experiments[str(i)] = json.load(f)

相关问题