nki*_*int 15 python configparser
这有点我没有python语法,我在读取.ini带插值的文件时遇到问题.
这是我的ini文件:
[DEFAULT]
home=$HOME
test_home=$home
[test]
test_1=$test_home/foo.csv
test_2=$test_home/bar.csv
Run Code Online (Sandbox Code Playgroud)
那些台词
from ConfigParser import SafeConfigParser
parser = SafeConfigParser()
parser.read('config.ini')
print parser.get('test', 'test_1')
Run Code Online (Sandbox Code Playgroud)
输出
$test_home/foo.csv
Run Code Online (Sandbox Code Playgroud)
虽然我在期待
/Users/nkint/foo.csv
Run Code Online (Sandbox Code Playgroud)
我认为$语法隐含在所谓的字符串插值中(参考手册):
除了核心功能之外,SafeConfigParser还支持插值.这意味着值可以包含引用同一节中其他值的格式字符串,或特殊DEFAULT节中的值.
但我错了.如何处理这种情况?
Mic*_*ico 23
首先根据您应该用于%(test_home)s插值的文档test_home.此外,密钥不区分大小写,您不能同时使用HOME和home密钥.最后,您可以使用SafeConfigParser(os.environ)考虑到您的环境.
from ConfigParser import SafeConfigParser
import os
parser = SafeConfigParser(os.environ)
parser.read('config.ini')
Run Code Online (Sandbox Code Playgroud)
哪里config.ini是
[DEFAULT]
test_home=%(HOME)s
[test]
test_1=%(test_home)s/foo.csv
test_2=%(test_home)s/bar.csv
Run Code Online (Sandbox Code Playgroud)
您可以在Python 3的情况下编写自定义插值:
import configparser
import os
class EnvInterpolation(configparser.BasicInterpolation):
"""Interpolation which expands environment variables in values."""
def before_get(self, parser, section, option, value, defaults):
return os.path.expandvars(value)
cfg = """
[section1]
key = value
my_path = $PATH
"""
config = configparser.ConfigParser(interpolation=EnvInterpolation())
config.read_string(cfg)
print(config['section1']['my_path'])
Run Code Online (Sandbox Code Playgroud)