PyQt/partner_625781186/15_Plugins/Tools/pmf_myjson.py

138 lines
3.7 KiB
Python
Raw Normal View History

# -*- coding: utf-8 -*-
"""
初始化json配置函数.
"""
from PyQt5.QtWidgets import *
from PyQt5.QtWidgets import QMessageBox , QWidget , QApplication
from PyQt5.QtCore import *
from subprocess import Popen
import json , os , sys
app = QApplication(sys.argv)
setting_path = "./PluginManager"
setting_Name = "plugin.json"
setting_flie = os.path.join(setting_path, setting_Name)
del app
if not os.path.exists(setting_path):
os.makedirs(setting_path)
if not os.path.exists(setting_path):
f1 = open(setting_flie, 'a+', encoding='utf-8')
f1.close()
name = {
}
def mfunc_readJson(f)->"datas":
'''
从头读取文件内容
'''
if isinstance(f , str) :
f = open(setting_flie, 'a+', encoding='utf-8')
#指针指向;
f.seek(0)
#读取;
text = f.read()
#json文本转为字典
datas= json.loads(text)
f.close()
#返回python字典
return datas
def mfunc_initJson( setting_flie ,self=None)->"datas":
'''
初始化创建json
@param setting_flie json路径
@type str
'''
with open( setting_flie ,'a+' , encoding='utf-8') as f:
if self == None:
self = QWidget()
try:
#存在 .json 才能成功;即第二次以后
datas = mfunc_readJson(f)
except:
#首次创建 数据默认为name
json.dump( name , f , ensure_ascii=False, indent=1)
try:
datas = mfunc_readJson(f)
except:
QMessageBox.warning(self, '配置文件格式错误',
'请严格按照JSON格式\n解决不了请联系程序员QQ62578186',
QMessageBox.Yes|QMessageBox.No, QMessageBox.No)
Popen(["write ", setting_flie])
finally:
return datas
2018-09-23 17:04:51 +08:00
def mfunc_AKrCVJson( key_name , data , self=None):
'''
修改json
@param key_name 要修改的json节点的键名
@type str or list-str
@param data 新数据
@type all
'''
if self == None:
self = QWidget()
with open( setting_flie ,'a+' , encoding='utf-8') as f:
datas = mfunc_initJson(setting_flie)
# 如果存在键名则替换 不存在则增加
if isinstance(key_name, str):
datas[key_name] = data
elif isinstance(key_name, list):
# TODO:
# 不存在键
if key_name[0] not in datas:
msg = QMessageBox.warning(self, '没有找到这个配置节点',
"请检查参数格式。\n如果配置不来请清空配置文件。\n是否打开配置文件?",
QMessageBox.Yes|QMessageBox.No, QMessageBox.No)
if msg==QMessageBox.Yes:
Popen(["write ", setting_flie])
elif msg==QMessageBox.No:
# TODO:
pass
return
else:
# == == == 构造命令文本
cmd_txt = "datas"
for key in key_name:
cmd_txt += (r'''["%s"]'''%key )
cmd_txt+='=data'
# == == == 执行命令文本
exec(cmd_txt)
# 清空原来的文件
f.seek(0)
f.truncate()
# 写入
json.dump( datas, f , ensure_ascii=False, indent=1)
2018-09-23 17:04:51 +08:00
def mfunc_reDumpJson(f , datas):
f.seek(0)
f.truncate()
# 写入
json.dump( datas, f , ensure_ascii=False, indent=1)