【python】configparser 读取配置文件

wx 读取配置文件,操作

# -*- coding: utf-8 -*-

###########################################################################
## Python code generated with wxFormBuilder (version 3.10.1-0-g8feb16b3)
## http://www.wxformbuilder.org/
##
## PLEASE DO *NOT* EDIT THIS FILE!
###########################################################################
import os

import wx
import wx.xrc

###########################################################################
## Class MyFrame
###########################################################################
import socket
import configparser

CONFIG_PATH = "setConfig.ini"


class MyFrame(wx.Frame):

    def __init__(self, parent):
        wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=u"Tools", pos=wx.DefaultPosition, size=wx.Size(600, 500),
                          style=wx.CAPTION | wx.CLOSE_BOX | wx.MINIMIZE_BOX | wx.SYSTEM_MENU | wx.TAB_TRAVERSAL)

        self.SetSizeHints(wx.DefaultSize, wx.DefaultSize)
        self.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_MENU))
        # self.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOW))

        main_gbSizer = wx.GridBagSizer(0, 0)
        main_gbSizer.SetFlexibleDirection(wx.BOTH)
        main_gbSizer.SetNonFlexibleGrowMode(wx.FLEX_GROWMODE_SPECIFIED)

        local_sbSizer = wx.StaticBoxSizer(wx.StaticBox(self, wx.ID_ANY, u"local"), wx.HORIZONTAL)

        local_sbSizer.SetMinSize(wx.Size(590, 100))
        self.local_staticText_ip = wx.StaticText(local_sbSizer.GetStaticBox(), wx.ID_ANY, u"本机IP", wx.DefaultPosition,
                                                 wx.DefaultSize, 0)
        self.local_staticText_ip.Wrap(-1)

        local_sbSizer.Add(self.local_staticText_ip, 0, wx.ALL, 5)

        self.local_textCtrl_ip = wx.TextCtrl(local_sbSizer.GetStaticBox(), wx.ID_ANY, wx.EmptyString,
                                             wx.DefaultPosition, wx.DefaultSize, 0)
        local_sbSizer.Add(self.local_textCtrl_ip, 0, wx.ALL, 5)

        self.local_staticText_port = wx.StaticText(local_sbSizer.GetStaticBox(), wx.ID_ANY, u"端口", wx.DefaultPosition,
                                                   wx.DefaultSize, 0)
        self.local_staticText_port.Wrap(-1)

        local_sbSizer.Add(self.local_staticText_port, 0, wx.ALL, 5)

        self.local_textCtrl_port = wx.TextCtrl(local_sbSizer.GetStaticBox(), wx.ID_ANY, wx.EmptyString,
                                               wx.DefaultPosition, wx.DefaultSize, 0)
        local_sbSizer.Add(self.local_textCtrl_port, 0, wx.ALL, 5)

        self.local_button_config = wx.Button(local_sbSizer.GetStaticBox(), wx.ID_ANY, u"修改配置", wx.DefaultPosition,
                                             wx.DefaultSize, 0)
        local_sbSizer.Add(self.local_button_config, 0, wx.ALL, 5)

        main_gbSizer.Add(local_sbSizer, wx.GBPosition(0, 0), wx.GBSpan(1, 1), wx.EXPAND, 5)

        self.SetSizer(main_gbSizer)
        self.Layout()

        self.Centre(wx.BOTH)
        self.local_textCtrl_ip.LabelText = socket.gethostbyname(socket.getfqdn(socket.gethostname()))
        self.local_textCtrl_port.LabelText = "8080"
        self.local_textCtrl_port.SetFocus()
        # 初始化加载配置文件
        self.local_config()
        # 绑定按钮事件
        self.local_button_config.Bind(wx.EVT_BUTTON, self.update_config)

    def __del__(self):
        pass

    # 默认加载当前目录下ini文件
    def local_config(self):
        # ini文件不存在,创建,存在则直接读取赋值
        print("加载ini配置文件....")
        # 文件当前路径
        current_path = os.path.dirname(os.path.realpath(__file__))
        print("当前路径:", current_path)
        # 获取路径下文件
        config_path = os.path.join(current_path, CONFIG_PATH)
        # 判断文件是否存在
        if os.path.exists(config_path):
            # 创建管理对象,读取配置文件
            config = configparser.ConfigParser()
            config.read(config_path, encoding="utf-8")
            # TODO:对配置文件进行操作
            # 获取所有的section
            sections = config.sections()
            print(sections)  # 返回list
            items = config.items('log_path')
            print(items)  # list里面对象是元祖
            print(items.pop(0))  # list里面对象是元祖
            print(config.get("log_path", "path"))  # list里面对象是元祖
            self.local_textCtrl_ip.LabelText = config.get("localhost", "HOST")
            self.local_textCtrl_port.LabelText = config.get("localhost", "PORT")
        else:
            # 新建配置文件并写入
            config = configparser.ConfigParser()
            config.add_section('localhost')
            config.set('localhost', 'HOST', '127.0.0.1')
            config.set('localhost', 'PORT', '3306')
            config.add_section('log_path')
            config.set('log_path', 'path', 'logs.log')
            with open(config_path, mode='w') as configfile:
                config.write(configfile)

    def update_config(self, event):
        # 更新配置文件,subprocess.run,使用Python 3.5+
        import subprocess
        subprocess.run(["notepad", CONFIG_PATH])

        # 打开方式2
        # os.system("notepad "+CONFIG_PATH)
        event.Skip


def main():
    app = wx.App(False)
    MyFrame(None).Show()
    app.MainLoop()


if __name__ == '__main__':
    main()

你可能感兴趣的:(python,开发语言)