温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python 之 读取配置文件ini

发布时间:2020-06-24 18:27:03 阅读:394 作者:余伟兵 栏目:编程语言
Python开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

    沿着在树莓派中开发瘦客户端连接远程桌面GUI程序这条主线,摸到了这里,使用pyqt5开发图形界面之后,程序读取一个ini配置文件,将远程连接的相关参数写到这个ini配置文件中。这样可以实现一个最简版的远程桌面连接程序。

    以上是背景,仅做一个记录。

    此文参考了这个网址:

    https://blog.csdn.net/songlh2234/article/details/83316468

一、读取配置文件

在config下有一个config.ini配置文件

#  定义config分组
[config]
platformName=Android
appPackage=com.romwe
appActivity=com.romwe.SplashActivity
 
#  定义cmd分组
[cmd]
viewPhone=adb devices
startServer=adb start-server
stopServer=adb kill-server
install=adb install aaa.apk
id=1
weight=12.1
isChoice=True
 
#  定义log分组
[log]
log_error=true

在test_config.py中编写读取配置文件的脚本代码

import configparser
 
#  实例化configParser对象
config = configparser.ConfigParser()
# -read读取ini文件
config.read('C:\\Users\\songlihui\\PycharmProjects\\AutoTest_02\\config\\config.ini', encoding='GB18030')
# -sections得到所有的section,并以列表的形式返回
print('sections:' , ' ' , config.sections())
 
# -options(section)得到该section的所有option
print('options:' ,' ' , config.options('config'))
 
# -items(section)得到该section的所有键值对
print('items:' ,' ' ,config.items('cmd'))
 
# -get(section,option)得到section中option的值,返回为string类型
print('get:' ,' ' , config.get('cmd''startserver'))
 
# -getint(section,option)得到section中的option的值,返回为int类型
print('getint:' ,' ' ,config.getint('cmd''id'))
print('getfloat:' ,' ' , config.getfloat('cmd''weight'))
print('getboolean:' ,'  ', config.getboolean('cmd''isChoice'))
"""
首先得到配置文件的所有分组,然后根据分组逐一展示所有
"""
for sections in config.sections():
    for items in config.items(sections):
        print(items)

执行结果:

C:\Users\think\.virtualenvs\RDPGUI-Oi_XG-yi\Scripts\python.exe D:/树莓派开发/RDPGUI/test/test_config.py
sections:   ['config''cmd''log']
options:   ['platformname''apppackage''appactivity']
items:   [('viewphone''adb devices'), ('startserver''adb start-server'), ('stopserver''adb kill-server'), ('install''adb install aaa.apk'), ('id''1'), ('weight''12.1'), ('ischoice''True')]
get:   adb start-server
getint:   1
getfloat:   12.1
getboolean:    True
('platformname''Android')
('apppackage''com.romwe')
('appactivity''com.romwe.SplashActivity')
('viewphone''adb devices')
('startserver''adb start-server')
('stopserver''adb kill-server')
('install''adb install aaa.apk')
('id''1')
('weight''12.1')
('ischoice''True')
('log_error''true')
Process finished with exit code 0

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI

开发者交流群×