【发布时间】:2023-01-14 02:57:06
【问题描述】:
我在这里有我的功能,可以读取我的配置文件。它只读取一个文件,但我希望它读取 2 个文件。我不确定如何合并另一个文件,以便我可以分别运行每个 data1 和 data2。
@staticmethod
def getConfig(env):
pwd=os.getcwd()
if "win" in (platform.system().lower()):
f = open(pwd+"\config_"+env.lower()+"_data1.json")
else:
f = open(pwd+"/config_"+env.lower()+"_data1.json")
config = json.load(f)
f.close()
return config
我想补充:
parser = argparse.ArgumentParser(description = 'Parse args for data program.',)
parser.add_argument('-f', '--db_env', action="store", dest="db_env")
args = parser.parse_args()
print('Running for Data:{}'.format(args.db_env))
所以我可以在命令行上运行它:
python datascript.py -f data1
或者
python datascript.py -f data2
我不知道如何将这两种方法结合在一起,我的函数只需要 1 个文件,但我可以选择在第二种方法中运行哪个文件?我糊涂了。这是我的另一个问题的跟进,我改变了我的策略并想选择在命令行中运行的文件。
更新 - - - - - - - - -
我将脚本更新为:
def getConfig(env):
pwd=os.getcwd()
env=env.lower()
json_paths = [Path(pwd, f"config_{env}_data2.json"), Path(pwd, f"config_{env}_data1.json")]
for path in json_paths:
with open(path, 'r') as f:
config = json.load(f)
f.close()
return config
它只返回我列出的第二个 Path(filename),所以它只返回 data1,并跳过 data2。如果我切换它们并让数据 2 秒,它将返回并跳过数据 1。
【问题讨论】:
-
注意:python 通常可以在 Windows 上使用
/打开路径。
标签: python json config argparse