典型的ConfigParser生成的文件如下所示:
[Section]
bar=foo
[Section 2]
bar2= baz
Run Code Online (Sandbox Code Playgroud)
现在,有没有办法索引列表,例如:
[Section 3]
barList={
item1,
item2
}
Run Code Online (Sandbox Code Playgroud)
本来我想问这个问题,但后来我发现之前已经想过......
谷歌搜索我发现这个扩展configparser的例子.以下适用于Python 3:
$ python3
Python 3.2.3rc2 (default, Mar 21 2012, 06:59:51)
[GCC 4.6.3] on linux2
>>> from configparser import SafeConfigParser
>>> class AmritaConfigParser(SafeConfigParser):
... def __init_(self):
... super().__init__()
...
>>> cfg = AmritaConfigParser()
Run Code Online (Sandbox Code Playgroud)
但不是Python 2:
>>> class AmritaConfigParser(SafeConfigParser):
... def __init__(self):
... super(SafeConfigParser).init()
...
>>> cfg = AmritaConfigParser()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __init__
TypeError: must be type, not classob
Run Code Online (Sandbox Code Playgroud)
然后我读了一下Python New Class和Old Class样式(例如 …
我曾尝试使用Python的ConfigParser模块来保存设置.对于我的应用程序,重要的是我在我的部分中保留每个名称的大小写.文档提到将str()传递给ConfigParser.optionxform()会实现这一点,但它对我不起作用.名称都是小写的.我错过了什么吗?
<~/.myrc contents>
[rules]
Monkey = foo
Ferret = baz
Run Code Online (Sandbox Code Playgroud)
我获得的Python伪代码:
import ConfigParser,os
def get_config():
config = ConfigParser.ConfigParser()
config.optionxform(str())
try:
config.read(os.path.expanduser('~/.myrc'))
return config
except Exception, e:
log.error(e)
c = get_config()
print c.options('rules')
[('monkey', 'foo'), ('ferret', 'baz')]
Run Code Online (Sandbox Code Playgroud) 在开发模式下,我有以下目录树:
| my_project/
| setup.py
| my_project/
| __init__.py
| main.py
| conf/
| myproject.conf
Run Code Online (Sandbox Code Playgroud)
我使用ConfigParser来解析myproject.conf文件.
在我的代码中,使用良好的路径加载文件很容易: my_project/conf/myproject.conf
问题是:当我使用setup.py安装我的项目时,配置文件位于(感谢setup.py)/etc/my_project/myproject.conf和我的应用程序中/usr/lib/python<version>/site-packages/my_project/.
如何my_project/conf/myproject.conf在"生产"模式下在项目中引用我的文件,并my_project/conf/myproject.conf在"devel"模式下引用本地文件().
另外,如果可能的话,我想要便携式(例如在Windows上工作).
这样做的好习惯是什么?
我想使用配置解析器从一个部分获取所有值
我用过这个,但它只给出了第一个值
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
Config = ConfigParser.ConfigParser()
Config.read("/etc/harvest.conf")
print ConfigSectionMap("files").values()
Run Code Online (Sandbox Code Playgroud) 如何在段内的给定文件中写注释?
如果我有:
import ConfigParser
with open('./config.ini', 'w') as f:
conf = ConfigParser.ConfigParser()
conf.set('DEFAULT', 'test', 1)
conf.write(f)
Run Code Online (Sandbox Code Playgroud)
我会得到这个文件:
[DEFAULT]
test = 1
Run Code Online (Sandbox Code Playgroud)
但是如何在[DEFAULT]部分内部获得包含注释的文件,例如:
[DEFAULT]
; test comment
test = 1
Run Code Online (Sandbox Code Playgroud)
我知道我可以通过以下方式将代码写入文件:
import ConfigParser
with open('./config.ini', 'w') as f:
conf = ConfigParser.ConfigParser()
conf.set('DEFAULT', 'test', 1)
conf.write(f)
f.write('; test comment') # but this gets printed after the section key-value pairs
Run Code Online (Sandbox Code Playgroud)
这是ConfigParser的可能吗?而且我不想尝试另一个模块,因为我需要尽可能地将我的程序保持为"库存".
ConfigParser是Python 备受争议的 vanilla配置解析器.
但是你可以简单地import config在哪里config.py有python代码来设置配置参数.
这两种配置方法的优点是什么?我什么时候应该选择?
我正在使用Python的ConfigParser来创建配置文件.我想检查某个部分是否定义了特定选项,如果有,则获取该值.如果没有定义选项,我只想继续没有任何特殊行为.似乎有两种方法可以做到这一点.
if config.has_option('Options', 'myoption'):
OPTION = config.get('Options', 'myoption')
Run Code Online (Sandbox Code Playgroud)
要么:
try:
OPTION = config.get('Options', 'myoption')
except ConfigParser.NoOptionError:
pass
Run Code Online (Sandbox Code Playgroud)
一种方法比另一种方法更受欢迎吗?在if涉及较少的线路,但我偶尔读到try/ except在很多情况下被认为更Python.
尝试使用日志配置文件来实现TimedRotatinigFileHandler.
由于某种原因,不会采取配置文件.
任何建议赞赏.
x.py:
import logging
import logging.config
import logging.handlers
logging.config.fileConfig("x.ini")
MyLog = logging.getLogger('x')
MyLog.debug('Starting')
Run Code Online (Sandbox Code Playgroud)
x.ini:
[loggers]
keys=root
[logger_root]
level=NOTSET
handlers=trfhand
[handlers]
keys=trfhand
[handler_trfhand]
class=handlers.TimedRotatingFileHandler
when=M
interval=1
backupCount=11
formatter=generic
level=DEBUG
args=('/var/log/x.log',)
[formatters]
keys=generic
[formatter_generic]
class=logging.Formatter
format=%(asctime)s %(levelname)s %(message)s
datefmt=
Run Code Online (Sandbox Code Playgroud)
Traceback (most recent call last):
File "x.py", line 5, in ?
logging.config.fileConfig("x.ini")
File "/usr/lib/python2.4/logging/config.py", line 76, in fileConfig
flist = cp.get("formatters", "keys")
File "/usr/lib/python2.4/ConfigParser.py", line 511, in get
raise NoSectionError(section)
ConfigParser.NoSectionError: No section: 'formatters'
Run Code Online (Sandbox Code Playgroud)
谢谢
哪个更适合为Python程序,内置模块(ConfigParser)或独立项目(ConfigObj)创建设置文件?
configparser ×10
python ×10
config ×1
configobj ×1
inheritance ×1
logging ×1
parsing ×1
python-2.x ×1
pythonpath ×1