[英]How to to extract data from ConfigParser
I'm building a cron job and data has to be read from a configuration file.我正在构建一个 cron 作业,并且必须从配置文件中读取数据。 I'm using the Python ConfigParser
module to achieve this, but I can't seem to read the data using the command-line argument and sub-command.我正在使用 Python ConfigParser
模块来实现这一点,但我似乎无法使用命令行参数和子命令读取数据。 I'm using Python argparse
module for command-line argument and sub-command.我将 Python argparse
模块用于命令行参数和子命令。 Help please.请帮忙。
Here is the configuration file:这是配置文件:
[ARGUMENTS]
n1=5
n2=7
Here is the code that does the work:这是完成工作的代码:
import argparse
import sys
import configparser
def main(number, other_number):
result = number * other_number
print(f'The result is {result}')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Running Cron Job...')
parser.add_argument('-n1', type=int, help='A number', default=1)
parser.add_argument('-n2', type=int, help='Another number', default=1)
parser.add_argument('--config', '-c', type=argparse.FileType('r'), help='config file')
args = parser.parse_args()
if args.config:
config = configparser.ConfigParser()
config.read_file(args.config)
# Transform values into integers
args.n1 = int(config['DEFAULT']['n1'])
args.n2 = int(config['DEFAULT']['n2'])
main(args.n1, args.n2)
This is the right answer to the question.这是问题的正确答案。
I found out that configuration files have section, with each section led by a section header, like this [SECTION]
, but my code in looking for a [DEFAULT]
section which does not exist in the configuration file, rather it contains an [ARGUMENT]
section header, instead of a [DEFAULT]
.我发现配置文件有部分,每个部分都由一个部分标题引导,就像这样[SECTION]
,但是我的代码在寻找配置文件中不存在的[DEFAULT]
部分,而是包含一个[ARGUMENT]
节标题,而不是[DEFAULT]
。
Here is the the config file should look like:这是配置文件应如下所示:
[DEFAULT]
n1=5
n2=7
Here is the right code to get config data:这是获取配置数据的正确代码:
NOTE: Code is fine, nothing was changed注意:代码很好,没有任何改变
...
...
...
if args.config:
config = configparser.ConfigParser()
config.read_file(args.config)
# Transform values into integers
args.n1 = int(config['DEFAULT']['n1'])
args.n2 = int(config['DEFAULT']['n2'])
main(args.n1, args.n2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.