Environment :Unix Python version : 2.7
I have a scenario where I am fetching some amount of data from an API and then storing it in a text file. I am running the python script with scheduled cron jobs of interval 30 minutes. while running it if the value of count is increased by 1 the previous value is changed to recent increased/decreased count if not then it runs same. what I am trying to implement is if the count is increased on first run it I will store the value temporarily then again on next run after 30 minutes comparison should happen with the previous value not the recent increased/decreased count, and then if the count is still increased/decreased then store it permanently and proceed further.
code
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
I am new to python can anybody help to acheive this ,what should I use in order to achieve this.
Your json file will look something like this
{
"latest": 5,
"history": [1, 2, 3, 4]
}
Basically, I am storing the recent node counts value as latest
and maintaining the history
(recent ones get appended at the end of it).
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.