我有一个python程序,可以在目标位置创建一些文件的键和值对,其中文件名是键,而生成的哈希键用作值。我正在使用md5checksum来检测文件中的更改。因此,在任何文件的内容发生任何变化的那一刻,我的程序都会检测到修改后的文件,并执行子流程模块中提到的一些CLI命令。下面是该程序的完整摘要。
import glob
import hashlib
import copy
import subprocess
import time
license_file = list(glob.iglob('<path_to>/*.lic'))
license_hashkey = dict()
def generate_md5checksum(license_file, ex="", inc=""):
hash_obj = hashlib.md5()
try:
fd = open(license_file,"rb")
except IOError:
print("Can't retrieve MD5sum for ", license_file)
pass
content = fd.readlines()
fd.close()
for eachLine in content:
if ex and eachLine.startswith(ex):
continue
hash_obj.update(eachLine)
hash_obj.update(inc.encode('utf-8'))
return hash_obj.hexdigest()
for key_value in license_file:
license_hashkey[key_value] = generate_md5checksum(key_value)
'''
Below program that compare the two copies of the dictionary and execute the lmreread on the license file that was updated with the new content.
'''
compare_license_key = copy.deepcopy(license_hashkey)
while True:
for keys in license_hashkey:
if license_hashkey[keys] != compare_license_key[keys]:
updated_license = list(license_hashkey.keys())[list(license_hashkey.values()).index(license_hashkey[keys])]
print("license hash key: " + license_hashkey[keys] + " compare license key: " + compare_license_key[keys])
subprocess.Popen(['lmutil', 'lmreread', '-c', updated_license])
time.sleep(12)
compare_license_key = copy.deepcopy(license_hashkey)
else:
print("hold tight, looking for a new or an updated license file")
time.sleep(1)
for key_value in license_file:
license_hashkey[key_value] = generate_md5checksum(key_value)
该程序的运行就像魅力一样。但是,我需要优化程序,以便即使多个用户在给定位置修改了不同的文件,我的代码也应该检测到它们,并可能创建这些文件的列表或字典,并在代码完成后立即执行CLI命令完成一个请求。目前,我的代码将对一个请求起作用,但是在处理这个请求时,它将无法捕获其他已修改的文件(如果有)。 我尝试的一种方式如下
1) Declare an empty list out of the "while" loop.
2) Run a "for" loop over the "updated_license" from my program inside the "while" loop.
3) Append the new list under the for loop in the point 2.
4) Run another "for" loop over the new list outside the "for" loop that is declare just below the "while" loop.
下面是优化的方法,但是它不起作用。
#lic_list = []
while True:
for keys in md5s:
if md5s[keys] != temp[keys]:
print("change detected")
license_file = list(md5s.keys())[list(md5s.values()).index(md5s[keys])]
#lic_list = [new for new in license_file]
#lic_list.append(lic_list)
subprocess.Popen(['lmutil', 'lmreread', '-c', license_file])
temp = copy.deepcopy(md5s)
else:
print("no change")
time.sleep(1)
#for i in lic_list:
# subprocess.Popen(['lmutil', 'lmreread', '-c', i])
for fname in file:
md5s[fname] = getmd5(fname)
# temp = copy.deepcopy(md5s)
# lic_list = []
注意:我已经对用于优化程序的行进行了哈希处理。