如何使用配置文件以不同的设置多次运行python文件?

时间:2019-03-13 16:23:21

标签: python json

我有一个 python脚本,它的设置位于一个单独的 json配置文件中。 json文件如下所示:

{
  "connection" : {
      "db_server" : "server",
      "db_name" : "table1", 
      "db_user" : "user1", 
}}

现在,我需要多次运行同一个python文件,每个配置文件中都有其他设置。其他设置如下所示:

{
  "connection" : {
      "db_server" : "server",
      "db_name" : "table2", 
      "db_user" : "user2", 
}}

我不需要更改Python脚本中的任何内容。我像这样在Python脚本中打开json文件:

with open('settings.json') as json_data_file:
    data = json.load(json_data_file)
    json_data_file.close()

由于您无法在json文件中添加评论,因此我不知道执行此操作的最简单方法。我希望Python脚本同时运行两次,每次使用json文件的其他设置。

谢谢!

2 个答案:

答案 0 :(得分:1)

  • 启动python脚本后,您可以就地修改配置文件并再次运行它。这不会影响已经在运行的python程序,因为他们已经读取了配置。
  • 或者您可以有多个具有不同名称的配置文件,然后使用某些命令行参数(即sys.argv[1])运行脚本以选择要使用的配置文件。我个人推荐这种方法。

答案 1 :(得分:0)

一个简单的解决方案是使用新脚本来解析JSON文件,导入Python脚本,然后使用concurrent使用不同的参数执行该脚本。

示例(adapted from the example for ThreadPoolExecutor)

import concurrent.futures
import json
from YourModule import MainFunction

# First, open and load your JSON file
parameter_dict = json.load(open('yourfilename.json'))

# Do some parsing to your parameters in order
# (In your case, servers, tables, and users)
parameters_to_submit = [[entry['db_server'], entry['db_table'], entry['db_user'] for entry in parameter_dict.values()]

# Now, generate a ThreadPool to run your script multiple times
with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
    # Submit the function + parameters to the executor
    submitted_runs = {
        executor.submit(MainFunction, params[0], params[1], params[2]): params
        for params in parameters_to_submit
    }

    # as the results come in, print the results
    for future in concurrent.futures.as_completed(submitted_runs):
        url = submitted_runs[future]
        try:
            data = future.result()
        except Exception as exc:
            print(f'Script generated an exception: {exc}')
        else:
            # if need be, you could also write this data to a file here
            print(f'Produced result {data}')
相关问题