如何在python中解析shell样式配置

2024-03-28 18:31:44 发布

您现在位置:Python中文网/ 问答频道 /正文

全部

我正在编写一些脚本,我有一个shell样式的配置文件,如下所示:

A=1
B=2

现在我必须编写一个python脚本,并使用这个配置文件获取一些值。有人说要使用python的ConfigureParser模块(像这样的代码),但我得到了错误。你知道吗

>>> import ConfigParser
>>> cf = ConfigParser.ConfigParser()
>>> cf.read("config")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ConfigParser.py", line 305, in read
    self._read(fp, filename)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ConfigParser.py", line 512, in _read
    raise MissingSectionHeaderError(fpname, lineno, line)
ConfigParser.MissingSectionHeaderError: File contains no section headers.
file: config, line: 1
'A=1\n'

我不能使用python ConfigParser样式的配置文件,这意味着配置文件与上面一样,无法更改它。那么如何在python中解析shell样式配置呢?~谢谢~


Tags: in脚本configread配置文件linelibrary样式
3条回答

尝试使用^{}方法分析配置字符串而不是文件名。然后可以使用字符串头更改内存中配置文件的格式:

import configparser

# Slurp in file contents
with open('example.cfg') as ec:
    cfg_data = ec.read()

# Insert a section header
cfg_data = "[default]\n\n" + cfg_data


# Now read the configuration:
cfgparser = configparser.ConfigParser()
cfgparser.read_string(cfg_data, source='example.cfg')
from configparser import ConfigParser
config = ConfigParser()
config.read('config')

print('IP' in config)
print(config.sections())
print((config['IP']['A']))

输出:

True
['IP']
1

试试这个。你知道吗

import configparser
config = configparser.RawConfigParser()

try:
    with open(YourConfigFilePath) as f:
        config.readfp(f)
except:
    print("Config file Don't exist.")

# Check the config variable
print(config)    

相关问题 更多 >