Python - 配置文件

Python - configuration file

我有代码:

import matplotlib.pyplot as plt
from configparser import ConfigParser  
cfg = ConfigParser()
cfg.read('file.cfg')    
plt.plot([1, 10],[2, 2], color_4, ls = "dashed")   
plt.xlim(1,10)
plt.ylim(1,4)
plt.savefig('image.pdf')

我想通过配置文件来控制它:

[a]
color_4 = c = 'silver'

请问有什么问题吗?它给出了一个错误:

NameError: name 'color_4' is not defined

我猜你需要这样取值才能得到color_4的值:

cfg['a']['color_4']

from configparser import ConfigParser  
cfg = ConfigParser()
cfg.read('file.cfg')    
plt.plot([1, 10],[2, 2], cfg['a']['color_4'], ls = "dashed")   
plt.xlim(1,10)
plt.ylim(1,4)
plt.savefig('image.pdf')

参考:ConfigParser