首页 > 解决方案 > 如何从主目录中的配置文件中读取值?

问题描述

.gitconfig在我的 HOME 目录中,格式如下:

cat ~/.gitconfig
[jenkins "https://myjenkins.com/ins1"]
       api-key = 12345abcd
[jenkins "https://myjenkins.com/ins2"]
       api-key = 1111aaaa

我需要读取 的api-keyins1,下面的代码有效,是否有更好或更 Pythonic 的方式?

>>> from configparser import ConfigParser
>>> from pathlib import Path
>>> config_object = ConfigParser()
>>> home = str(Path.home())
>>> config_object.read(f'{home}/.gitconfig')
>>> ins = "https://myjenkins.com/ins1"
>>> config_object[f'jenkins "{ins}"']['api-key']
'12345abcd'

标签: python-3.6configparser

解决方案


推荐阅读