【问题标题】:reading config file in python with ConfigParser使用 ConfigParser 在 python 中读取配置文件
【发布时间】:2021-01-13 16:44:58
【问题描述】:

我使用 configparser 在我的 python 编写程序中读取配置。我现在正在从 s3 读取文件,但我的要求是在程序本身而不是从任何其他外部源中定义的配置。 编写代码如下:

config = configparser.ConfigParser()
config.readfp(open(s3:path\config))

配置文件格式: 配置.ini

[section1]
var1=Y
var2=Y
var3=['col1','col2']

我正在阅读位于 s3 中的上述文件,但我不想从 s3 中读取,而是想从程序本身中读取。为了实现这一目标需要做什么?

上面的代码是用 pyspark 程序编写的,我正在使用 spark submit 命令传递配置文件,但是要读取配置文件,我需要提供路径,这是不可取的。 spark 在 aws emr 中提交:

'Args': ['spark-submit','--deploy-mode', 'cluster','--master', 'yarn','--executor-memory', conf['emr_step_executor_memory'],'--executor-cores',  conf['emr_step_executor_cores'],'--conf','spark.yarn.submit.waitAppCompletion=true','--conf','spark.rpc.message.maxSize=1024',f'{s3_path}/file1.py',  '--py-files',f'{s3_path}/file2.py',f'{s3_path}/file3.py',f'{s3_path}/file4.py','--files', f'{s3_path}/config ]

因为 config.readfp(open(s3:path\config)) 行,我需要提供 s3 路径,这是不可取的选项,要么从 spark 提交传递配置文件,要么使所有其他正在阅读的 python 文件可用配置或读取程序本身内部的配置。

【问题讨论】:

  • 拥有配置文件的全部目的是从代码中分离运行时配置值。如果您不想这样做,请使用 configparser 将配置写入到一个临时位置并将其传递给 Spark。

标签: python apache-spark amazon-s3 config configuration-files


【解决方案1】:

你可以这样做:

parser = configparser.ConfigParser()
parser.read_dict({'section1': {'key1': 'value1',
                                'key2': 'value2',
                                'key3': 'value3'},
                   'section2': {'keyA': 'valueA',
                                'keyB': 'valueB',
                                'keyC': 'valueC'},
                   'section3': {'foo': 'x',
                                'bar': 'y',
                                'baz': 'z'}})

查看this 了解详细信息以及实现此目的的其他替代方法。

样本检索

parser["section1"]["key1"]
'value1'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-28
    • 2011-05-01
    相关资源
    最近更新 更多