工具类
ConfigParser
文件路径
当前文件路径,使用os模块
curpath = os.path.dirname(os.path.realpath(__file__)) #当前文件路径
读取配置文件及字段
self.config = configparser.ConfigParser() #使用工具类读写ini配置文件
self.config.read(self.configPath,encoding="utf-8")
ip = self.config['net_config']['ip']
修改配置文件内容
#修改配置文件IP
def setIpConfing(self,ip):
self.config.set('net_config','ip',ip)
self.config.write(open(self.configPath, 'w'))
获取当前路径对应的磁盘空间(Windows)
使用工具shutil
(total,used,free) = shutil.disk_usage(os.path.abspath('.')[:3]) #获取磁盘空间
gb = 1024 ** 3
self.freeDisk = free / gb
print("获取路径:",os.path.abspath('.')[:3])
print('可用空间: {:6.2f} GB '.format( self.freeDisk))
完整代码块
import configparser
import os
import socket
import shutil
import sys
class Config():
__netIp = "127.0.0.1"
port = 8081
saveFileDir = "fileData"
currentEnvPath = ""
instance = None
freeDisk = 0.0
def getNetIp(self):
# print("addr:"+ self.__netIp)
return self.__netIp
def setNetIp(self,value):
self.__netIp = value
def __new__(cls, *args, **kwargs): # 使其为单例模式
if cls.instance is None:
cls.instance = super().__new__(cls)
return cls.instance
def initConfig(self):
if hasattr(sys, '_MEIPASS'): # 解决打包成exe的时候路径问题
curpath = os.path.dirname(os.path.realpath(sys.executable))
# curpath = os.path.dirname(os.path.dirname(sys.argv[0]))
else:
curpath = os.path.dirname(os.path.realpath(__file__)) #当前文件路径
self.currentEnvPath = curpath
self.configPath = os.path.join(curpath,'config.ini')
self.config = configparser.ConfigParser() #使用工具类读写ini配置文件
self.config.read(self.configPath,encoding="utf-8")
ip = self.config['net_config']['ip']
if ip == '127.0.0.1':
r = socket.gethostbyname(socket.gethostname()) #获取本机IP
self.setNetIp(r)
else:
self.setNetIp(ip)
self.port = int(self.config['net_config']['port'],10)
self.saveFileDir = self.config['file_path_config']['rootDir']
(total,used,free) = shutil.disk_usage(os.path.abspath('.')[:3]) #获取磁盘空间
gb = 1024 ** 3
self.freeDisk = free / gb
print("获取路径:",os.path.abspath('.')[:3])
print('可用空间: {:6.2f} GB '.format( self.freeDisk))
print("获取配置ip:",self.__netIp)
print("获取配置端口:",self.port)
print("获取配置文件目录:",self.saveFileDir)
print(os.path.join(curpath,self.saveFileDir))
#修改配置文件IP
def setIpConfing(self,ip):
self.config.set('net_config','ip',ip)
self.config.write(open(self.configPath, 'w'))
if __name__ == "__main__":
gConfig = Config()
gConfig.initConfig()
配置文件config.ini
[net_config]
ip = 127.0.0.1
port = 8081
[file_path_config]
rootdir = fileData