Python脚本用来更改json配置文件

try:
import json
except ImportError:
import simplejson as json


import os


class UpdateTQPConfig(object):
def __init__(self, config_filepath):
if config_filepath:
self.config_filepath = config_filepath


def __del__(self):
pass

def set_tqp_switch(self, tqpList, flag):


if type(tqpList) != list:
return False


fp1 = open(self.config_filepath, 'r')
if fp1:
tqp_conf = json.load(fp1)
fp1.close()


print "Update TQP cofiguration file: %s..." % self.config_filepath
for tqp in tqpList:
if not tqp_conf.has_key(tqp):
print 'Add one entry : %s %d' %(tqp, flag)
tqp_conf[tqp] = flag
else:
print 'Edit one entry : %s %d' %(tqp, flag)
tqp_conf[tqp] = flag


#print tqp_conf
fp2 = open(self.config_filepath, 'w')
json.dump(tqp_conf, fp2, indent=2)


fp2.close()


def restart_service(self, command):
command = '%s restart' % command
print "%s ..." % command
os.popen(command)


if __name__ == '__main__':


tqpList = ["EmailTasks", "RootedTasks", "testTasks"]
cf = UpdateTQPConfig('/etc/sysconfig/tqp/plugins.json')
cf.set_tqp_switch(tqpList, 0)


cf.restart_service("/etc/init.d/task-processor")


--------------------------------------------------------------------------------------------------------------------

def get_json_data(self, filepath):
try:
fp1 = open(filepath, 'r')
except Exception, e:
print "Exception: %s" % str(e)
if fp1:
rest = json.load(fp1)
fp1.close()
return rest
pass


def set_json_data(self, filepath, key, value):


if not key or not value:
print 'key or value is invalid for update %s!' % filepath
return 


fp1 = open(filepath, 'r')
if fp1:
tqp_conf = json.load(fp1)
fp1.close()


print "Update TQP cofiguration file: %s..." % filepath
if not tqp_conf.has_key(key):
print 'Add one entry : %s %s' %(key, value)
tqp_conf[key] = value
else:
print 'Edit one entry : %s %s' %(key, value)
tqp_conf[key] = value


#print tqp_conf
fp2 = open(filepath, 'w')
#json.dump(tqp_conf, fp2, indent=2)  
json.dump(tqp_conf, fp2)  


fp2.close()
pass

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值