How do I put a semicolon in a value in python configparser?

旧时模样 提交于 2019-12-24 02:23:19

问题


I need to specify a password on the right side of the equals sign in a python configparser file, but semicolon is the comment character.

Escaping with \ does not work.

How can I pass the string "foo;" as a value in configparser?


回答1:


A short interactive session shows the semicolon is read without trouble.

>>> import StringIO
>>> import ConfigParser
>>> f = StringIO.StringIO("[sec1]\npwd=foo;\n")
>>> p = ConfigParser.ConfigParser()
>>> p.readfp(f)
>>> p.items('sec1')
[('pwd', 'foo;')]
>>> 



回答2:


ConfigParser seems to have a bug with spaces in front of semicolons:

>>> import StringIO
>>> import ConfigParser
>> p = ConfigParser.ConfigParser()
>>> s1 = StringIO.StringIO('[foo]\nbla=bar;baz\n')
>>> p.readfp(s1)
>>> p.items('foo')
[('bla', 'bar;baz')]

>>> s2 = StringIO.StringIO('[foo]\nbla=bar ;-) baz\n')
>>> p.readfp(s2)
>>> p.items('foo')
[('bla', 'bar')]

>>> s3 = StringIO.StringIO('[foo]\nbla=bar \;-) baz\n')
>>> p.readfp(s3)
>>> p.items('foo')
[('bla', 'bar \\;-) baz')]
>>>

Note that the last version is still incorrect, because the escape backslash is still in there...




回答3:


Mine works fine. And noticed "Lines beginning with '#' or ';' are ignored and may be used to provide comments. "



来源:https://stackoverflow.com/questions/4298073/how-do-i-put-a-semicolon-in-a-value-in-python-configparser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!