我有一个由称为system.config的配置文件控制的python脚本。配置文件的结构就像下面这样,带有一些默认值。
[company]
companyname: XYZ
[profile]
name: ABC
joining: 1/1/2014
配置文件的代码是:config_parser_details.py
import ConfigParser
import sys
Config = ConfigParser.ConfigParser()
Config.read("system.config")
filename = "system.config"
def ConfigSectionMap(section):
dict1 = {}
options = Config.options(section)
for option in options:
try:
dict1[option] = Config.get(section, option)
if dict1[option] == -1:
DebugPrint("skip: %s" % option)
except:
print("exception on %s!" % option)
dict1[option] = None
return dict1
company = ConfigSectionMap("company")['companyname']
name = ConfigSectionMap("profile")['name']
joindate = ConfigSectionMap("profile")['joining']
现在我脚本的代码是:test.py
import config_parser_details as p
import sys
import warnings
import os
company = p.company
name = p.name
date = p.joindate
print("%s\n" %company)
print("%s\n" %name)
输出是
XYZ
ABC
现在我想通过命令行在配置文件中输入内容。喜欢
python test.py --compname ="testing"
如果命令行中缺少任何参数,则将输入默认值。
您可以使用argparse库来解析命令行参数。
因此,您的test.py文件如下所示:
import config_parser_details as p
import sys
import warnings
import os
import argparse
commandLineArgumentParser = argparse.ArgumentParser()
commandLineArgumentParser.add_argument("-c", "--compname", help="Company name", default=p.company)
commandLineArguments = commandLineArgumentParser.parse_args()
company = commandLineArguments.compname
name = p.name
date = p.joindate
print("%s\n" %company)
print("%s\n" %name)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句