简体   繁体   English

在python中使用configparser

[英]using configparser in python

Sorry, I am a newbie in Python and trying to work on the ConfigParser module. 抱歉,我是Python的新手,正在尝试使用ConfigParser模块。 Here is one script which is used to read multiple sections and values from a .ini file and print them as below (Current output). 这是一个脚本,用于从.ini文件中读取多个节和值,并如下所示打印它们(当前输出)。 Now, I would like to store each of these values of url, password into variables and use each of them to run REST call using a for loop. 现在,我想将url,password的每个值存储到变量中,并使用它们中的每个值通过for循环运行REST调用。

What changes are required to store value of each "url" and "password" into different variables? 为了将每个“ URL”和“密码”的值存储到不同的变量中,需要进行哪些更改?

# cat file.ini

[bugs]
url = http://localhost:1010/bugs/
username = mark
password = SECRET

[wiki]
url = http://localhost:1010/wiki/
username = chris
password = PWD

Script :- 剧本:-

from ConfigParser import SafeConfigParser

parser = SafeConfigParser()
parser.read('file.ini')

for element in parser.sections():
    print 'Section:', element
    print '  Options:', parser.options(element)
    for name, value in parser.items(element):
        print '  %s = %s' % (name, value)
    print

Current output :- 电流输出

~]# python parse.py

Section: wiki
  Options: ['url', 'username', 'password']
  url = http://localhost:1010/wiki/
  username = chris
  password = PWD

Section: bugs
  Options: ['url', 'username', 'password']
  url = http://localhost:1010/bugs/
  username = mark
  password = SECRET
# The format is parser.get(section, tag)
bugs_url = parser.get('bugs', 'url')
bugs_username = parser.get('bugs', 'username')
bugs_password = parser.get('bugs', 'password')

wiki_url = parser.get('wiki', 'url')
wiki_username = parser.get('wiki', 'username')
wiki_password = parser.get('wiki', 'password')
from ConfigParser import SafeConfigParser

parser = SafeConfigParser()
parser.read('file.ini')

config_dict = {}

for element in parser.sections():
    print 'Section:', element
    config_dict[element] = {}
    print '  Options:', parser.options(element)
    for name, value in parser.items(element):
        print '  %s = %s' % (name, value)
        config_dict[element][name] = value

print config_dict

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM