『壹』 如何使用Python3读取配置文件
ini文件简介
ini是我们常见到的配置文件格式之一。
ini是微软Windows操作系统中的文件扩展名(也常用在其他系统)。
INI是英文“初始化(Initial)”的缩写。正如该术语所表示的,INI文件被用来对操作系统或特定程序初始化或进行参数设置。
网络
通过它,可以将经常需要改变的参数保存起来(而且还可读),使程序更加的灵活。
我先给出一个ini文件的示例。
[School]
ip = 10.15.40.123
mask = 255.255.255.0
gateway = 10.15.40.1
dns = 211.82.96.1
[Match]
ip = 172.17.29.120
mask = 255.255.255.0
gateway = 172.17.29.1
dns = 0.0.0.0
这个配置文件中保存的是不同场合下的IP设置参数。
下面将以生成和读取这个配置文件为例,进行讲解。
Python(v3)读取方法
首先,Python读取ini配置需要用到ConfigParser包,所以要先加载它。
import configparser
之后我们需要载入配置文件。
config=configparser.ConfigParser()
#IpConfig.ini可以是一个不存在的文件,意味着准备新建配置文件。
config.read("IpConfig.ini")
接下来,我们可以使用configparser.add_section()向配置文件中添加一个Section。
#添加节School
config.add_section("School")
注意:如果文件中已经存在相应的项目,则不能再增加同名的节。
然后可以使用configparser.set()在节School中增加新的参数。
#添加新的IP地址参数
config.set("School","IP","192.168.1.120")
config.set("School","Mask","255.255.255.0")
config.set("School","Gateway","192.168.1.1")
config.set("School","DNS","211.82.96.1")
你可以以同样的方式增加其它几项。
#由于ini文件中可能有同名项,所以做了异常处理
try:
config.add_section("Match")
config.set("Match","IP","172.17.29.120")
config.set("Match","Mask","255.255.255.0")
config.set("Match","Gateway","172.17.29.1")
config.set("Match","DNS","0.0.0.0")
except configparser.DuplicateSectionError:
print("Section 'Match' already exists")
增加完所有需要的项目后,要记得使用configparser.write()进行写入操作。
config.write(open("IpConfig.ini", "w"))
以上就是写入配置文件的过程。
接下来我们使用configparser.get()读取刚才写入配置文件中的参数。读取之前要记得读取ini文件。
ip=config.get("School","IP")
mask=config.get("School","mask")
gateway=config.get("School","Gateway")
dns=config.get("School","DNS")
print((ip,mask+"\n"+gateway,dns))
完整示例
下面是一个完整的示例程序,他将生成一个IpConfig.ini的配置文件,再读取文件中的数据,输出到屏幕上。
# -*- coding: utf-8 -*-
import configparser
#读取配置文件
config=configparser.ConfigParser()
config.read("IpConfig.ini")
#写入宿舍配置文件
try:
config.add_section("School")
config.set("School","IP","10.15.40.123")
config.set("School","Mask","255.255.255.0")
config.set("School","Gateway","10.15.40.1")
config.set("School","DNS","211.82.96.1")
except configparser.DuplicateSectionError:
print("Section 'School' already exists")
#写入比赛配置文件
try:
config.add_section("Match")
config.set("Match","IP","172.17.29.120")
config.set("Match","Mask","255.255.255.0")
config.set("Match","Gateway","172.17.29.1")
config.set("Match","DNS","0.0.0.0")
except configparser.DuplicateSectionError:
print("Section 'Match' already exists")
#写入配置文件
config.write(open("IpConfig.ini", "w"))
ip=config.get("School","IP")
mask=config.get("School","mask")
gateway=config.get("School","Gateway")
dns=config.get("School","DNS")
print((ip,mask+"\n"+gateway,dns))
『贰』 【Python基础】PIP 镜像源配置轻松搞定
pip 是 python 必不可少的的包管理工具,但是要在国内用得爽,必须要配置镜像源。
有哪些镜像站可用,以及如何配置,网上都有很多分享了。
我常用的是 阿里云镜像站 。
这里有一点比较麻烦的地方,就是是 linux 和 Windows 环境下的 pip 配置文件的名字和位置都不同,经常混淆。
今天就教大家一招,快速搞定:
执行完上面两条命令就可以啦。
pip config set 命令能自动把配置写入到用户对应的配置文件中:
[global]
index-url = https://mirrors.aliyun.com/pypi/simple/
[install]
trusted-host=mirrors.aliyun.com
命令虽然方便,但是参数格式复杂,记住不太容易,要是想改一下也挺麻烦,
所以我们进一步了解一下细节。
“ 下面我以 Windows 系统为例,实际在 Linux 系统也是类似
查看配置
执行 pip config list 命令可以显示已经有了哪些配置:
pip config list
global.index-url='http://mirrors.aliyun.com/pypi/simple/'
install.trusted-host='mirrors.aliyun.com'
带上一个 -v 选项:
pip config list -v
For variant 'global', will try loading 'C:\ProgramData\pip\pip.ini'
For variant 'user', will try loading 'C:\Users\davy\pip\pip.ini'
For variant 'user', will try loading 'C:\Users\davy\AppData\Roaming\pip\pip.ini'
For variant 'site', will try loading 'c:\users\davy\appdata\local\programs\python\python38\pip.ini'
global.index-url='http://mirrors.aliyun.com/pypi/simple/'
install.trusted-host='mirrors.aliyun.com'
“ 这里有一点不太好的地方是不显示配置是在哪个文件里。
就把它尝试获取的配置文件名完整路径列出来了。前面的 global 和 user 和 site 分别表示配置文件生效的范围:
global - 全局,一般不用
user - 当前用户,推荐
site - 只针对某一个 python 解释器
可以看到 user 有两个地方,其中配置任何一个都是可以的。
有的网络文章推荐的手动创建文件地址是前面那个,但是 pip 默认创建的是后者。
编辑配置
在命令行直接执行 pip config edit 会自动为我们打开配置文件,但是在 Windows 环境下还不行:
pip config edit
ERROR: Could not determine editor to use.
需要手动指定一个编辑器,就用记事本就行了:
pip config edit --editor notepad
“ Linux 系统中编辑器可以使用 vi,也可以是你习惯的其它编辑器
如果你从来没有设置过,它会报 找不到指定路径,这是因为相应的文件夹没有创建。
设置配置
通过 pip config set 命令可以直接设置配置项,它会自动创建没有的文件夹和文件。但是必须要给定一个配置项:
pip config set
ERROR: Got unexpected number of arguments, expected 2. (example: "pip config set [name] [value]")
我们随便写一个配置:
pip config set x.y z
Writing to C:\Users\davy\AppData\Roaming\pip\pip.ini
然后再执行上面的
pip config edit --editor notepad
就能自动打开配置文件,把拷贝好的配置文件内容贴进去就可以啦。
『叁』 python 怎么读取配置文件
python 读取配置文件方法
#coding=utf8
import ConfigParser
config = ConfigParser.ConfigParser()
config.readfp(open(raw_input("input file name:"), "rb"))
print config.get("global", "ip")
config.ini
[global]
ip = 192.168.1.100 ;ip地址
port = 3306
『肆』 linux新安装python怎么配置文件
首先把
Boost库
的
头文件
存放到/usr/include/boost/路径下,再把
Lib文件
存放到/usr/local/lib/boost/路径下。修改/etc/profile文件,在此文件中增加如下2个
环境变量
:
BOOST_INCLUDE=/usr/include/boost
export
BOOST_INCLUDE
BOOST_LIB=/usr/loca...
『伍』 python 如何修改配置文件(ini)的section名称
deffunc():
input=open(r"c: est.ini")
lines=input.readlines()
input.close()
output=open(r"c: ewest.ini",'w');
forlineinlines:
ifnotline:
break
if'name'inline:
temp=line.split("name")
temp1=temp[0]+'myname'+temp[1]
output.write(temp1)
else:
output.write(line)
output.close()
if__name__=='__main__':
func()
『陆』 Python 快速检测配置文件是否变更
分享背景:
当项目非常多时随之而来的配置文件也会变得非常多,而且越发的复杂,有时候上线后才知道线上环境的配置文件不对,那么我们如何提前来检测到配置文件有改动了,本文将给你提供一个可以检测的手段。代码如下所示
1.导入包并指定目录
2.初始化配置文件的md5值并入库
3.检测新配置文件的md5值是否变化
4.文件进行md5加密处理
5.遍历指定目录下文件
6.代码运行入口
总结:
我们首先要确定我们要检测的配置文件,然后将它的当前的md5值进行初始化到数据库,当下次发布前我们可以针对性的进行一次检测,发现有变更就会提示出来,这样就可以做到提前知晓变更的配置文件,再人工介入进行重点检查。
『柒』 python 如何实现配置文件中的配置项加密
可以在写入配置文件的时候,进行加密,读取配置后解密即可
比如使用base64加密:
base64.b64encode加密,base64.b64decode解密
『捌』 如何动态修改python logging配置文件
配置文件:
#Configuration for log output
#Naiveloafer
#2012-06-04
[loggers]
keys=root,xzs
[handlers]
keys=consoleHandler,fileHandler,rotatingFileHandler
[formatters]
keys=simpleFmt
[logger_root]
level=DEBUG
#handlers=consoleHandler
#handlers=fileHandler
handlers=rotatingFileHandler
[logger_xzs]
level=DEBUG
handlers=rotatingFileHandler
qualname=xzs
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFmt
args=(sys.stdout,)
[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=simpleFmt
args=("../log/p2pplayer.log", "a")
[handler_rotatingFileHandler]
class=handlers.RotatingFileHandler
level=DEBUG
formatter=simpleFmt
args=("../log/p2pplayer.log", "a", 20*1024*1024, 10)
[formatter_simpleFmt]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s - [%(filename)s:%(lineno)s]
datefmt=
测试代码:
def log_test02():
import logging
import logging.config
CONF_LOG = "../conf/p2pplayer_logging.conf"
logging.config.fileConfig(CONF_LOG); # 采用配置文件
logger = logging.getLogger("xzs")
logger.debug("Hello xzs")
logger = logging.getLogger()
logger.info("Hello root")
if __name__ == "__main__":
log_test02()
输出:
2012-06-04 15:28:05,751 - xzs - DEBUG - Hello xzs - [xlog.py:29]
2012-06-04 15:28:05,751 - root - INFO - Hello root - [xlog.py:32]
具体就不详细说明了,总之是能够运行的,这个文件配置搞了我两天时间。
特别是class=XXXX要注意!!!