为Python程序创建配置文件 [英] Creating a config file for Python Program

查看:65
本文介绍了为Python程序创建配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个小的Python GUI,用于控制MCU板的I2C引脚.现在,我想尝试将此GUI的设置保存到配置文件中,以便可以根据所使用的MCU更改文件设置.

I have created a small Python GUI for controlling the I2C pins of my MCU board. Now I want to try and save the settings of this GUI into a config file, so that the file settings could be changed based on the MCU being used.

我不知道如何创建配置文件.我试图研究有关如何创建和使用配置文件(例如 ConfigParse )的链接,但了解得不多.有人可以帮我吗?

I have no idea how to create a config file. I tried to looking into links on how to create and use a config file (e.g. ConfigParse), but could not understand much. Can somebody please help me out?

我正在Windows 7上使用Python 3.4.

I am using Python 3.4 on Windows 7.

推荐答案

使用 ConfigParser !链接的文档在使用它进行编程时应该会非常有用.

You're on the right tracks with using ConfigParser! Linked are the docs that should be very useful when programming using it.

对您来说,最有用的想法可能是示例,可以在以下示例中找到它们

For you, the most useful think will likely be the examples, which can be found here. A simple program to write a config file can be found below

import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {'ServerAliveInterval': '45',
                     'Compression': 'yes',
                     'CompressionLevel': '9'}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Port'] = '50022'     # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
  config.write(configfile)

该程序将一些信息写入文件"example.ini".读取此内容的程序:

This program will write some information to the file "example.ini". A program to read this:

import configparser
config = configparser.ConfigParser()
config.read('example.ini')
print(config.sections()) #Prints ['bitbucket.org', 'topsecret.server.com']

然后,您可以像使用其他任何词典一样简单地使用它.访问像这样的值:

Then you can simply use it like you would any other dictionary. Accessing values like:

config['DEFAULT']['Compression'] #Prints 'yes'

给予python文档的信用.

Credit given to python docs.

这篇关于为Python程序创建配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆