环境:Unix Python版本:2.7
我有一个场景,我从API中获取一些数据,然后将其存储在文本文件中。 我正在使用间隔30分钟的预定cron作业运行python脚本。 如果count的值增加1,则运行它时,如果没有,则先前的值增加/减少,然后运行相同。 我想要实现的是,如果计数在第一次运行时增加,我会暂时存储该值,然后在下一次运行后再次运行30分钟后应该与之前的值进行比较,而不是最近增加/减少的计数,然后如果计数仍然增加/减少然后永久存储并继续进行。
码
def app_counts():
while True:
try:
url_node = os.popen("ApiURL").read()
node_data = json.loads(url_node)
except BaseException as exp:
continue
break
process_num = (node_data[0]["proc"])
node_count = len(process_num)
print ("...........................................")
f_check = file("/home/user/app_check/file.txt",'r')
f_data = f_check.read()
chk_data = int(f_data)
############################write increased count to file######################################################
f1 = open("file.txt", "w")
n1 = f1.write(str(node_count) + "\n")
f1.close() #Here I want to store the current increased count temporarily(for example if count is increased/decreased store it temporarily and from next run compare it from previous one still if it is increased then store permanently)
def app_acc():
comp_n = recent_node_counts()
f2 = file("/home/user/app_check/file.txt",'r') ## reads last value of count
r_data = f2.read()
cmp_n = int(r_data)
if(comp_n < cmp_n ):
sys.exit(1) ### fail the build forcefully
else:
print ('OK ')
print 'recent count = ', comp_n
我是python的新手,任何人都可以帮助实现这个目标,我应该用什么才能实现这个目标。
答案 0 :(得分:0)
你的json文件看起来像这样
{
"latest": 5,
"history": [1, 2, 3, 4]
}
基本上,我将最近的节点计数值存储为latest
并维护history
(最近的节点计数值附加在它的末尾)。
import json
def get_data():
# read json file data from previous run
with open("/home/user/app_check/file.txt") as f_check:
data = json.load(f_check)
return data
def app_counts():
...
node_count = len(process_num)
...
data = get_data()
# if value is increased from last, store it permanently
if data['latest'] < node_count:
data['history'].append(node_count)
# update latest temporary count
data['latest'] = node_count
# write to json file
with open("file.txt", "w") as f1:
json.dump(data, f1)
def app_acc():
comp_n = recent_node_counts()
data = get_data()
if(comp_n < data['latest']):
sys.exit(1) ### fail the build forcefully
else:
print ('OK ')
print 'recent count = ', comp_n