【问题标题】:Is there a version of ConfigParser that deals with files with no section headers?是否有处理没有节标题的文件的 ConfigParser 版本?
【发布时间】:2012-03-13 14:36:33
【问题描述】:

我有一个主要用于shell脚本的配置文件,因此格式如下:

# Database parameters (MySQL only for now)
DBHOST=localhost
DATABASE=stuff
DBUSER=mypkguser
DBPASS=zbxhsxhg

# Storage locations
STUFFDIR=/var/mypkg/stuff
GIZMODIR=/var/mypkg/gizmo

现在我需要从 Python (2.6) 脚本中读取它的值。我不想重新发明轮子并用descriptor.readlines() 解析它,并寻找等号并跳过以“#”开头的行并处理引用的值和等等等等无聊。我尝试使用 ConfigParser,但它不喜欢没有节标题的文件。我有什么选择吗?还是我必须做这件无聊的事?

哦,顺便说一下,在 Python 脚本周围包裹一个 shell 脚本不是一种选择。它必须在 Apache 中运行。

【问题讨论】:

  • 这是this question的副本吗?
  • Akk.是的。这是一个精确的副本。对不起。

标签: python python-2.7 configparser


【解决方案1】:

我不知道这样的模块,但作为一种快速而肮脏的 hack - 只需在文件内容之前添加 [section],您就可以按预期使用 ConfigParser!

from io import StringIO

filename = 'ham.egg'
vfile = StringIO(u'[Pseudo-Sectio]\n%s'  % open(filename).read())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-22
    • 2017-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-20
    • 2012-04-17
    • 1970-01-01
    相关资源
    最近更新 更多