假设我有一个程序A.我运行它,并从文件foo.txt开始执行一些操作.现在A终止了.
A的新运行.它检查文件foo.txt是否已更改.如果文件已更改,则A再次运行其操作,否则退出.
是否存在库函数/外部库?
当然,它可以用md5 +包含md5的文件/ db来实现.我想防止重新发明轮子.
Suf*_*ian 10
不太可能有人为了这么简单的事情而建立了一个库.13行解决方案:
import pickle
import md5
try:
l = pickle.load(open("db"))
except IOError:
l = []
db = dict(l)
path = "/etc/hosts"
checksum = md5.md5(open(path).read())
if db.get(path, None) != checksum:
print "file changed"
db[path] = checksum
pickle.dump(db.items(), open("db", "w")
Run Code Online (Sandbox Code Playgroud)
仅供参考-对于使用此示例的人,该错误发生:“ TypeError:无法腌制HASH对象”只需修改以下内容(可选地将md5更新为hashlib,不建议使用md5):
import pickle
import hashlib #instead of md5
try:
l = pickle.load(open("db"))
except IOError:
l = []
db = dict(l)
path = "/etc/hosts"
#this converts the hash to text
checksum = hashlib.md5(open(path).read()).hexdigest()
if db.get(path, None) != checksum:
print "file changed"
db[path] = checksum
pickle.dump(db.items(), open("db", "w"))
Run Code Online (Sandbox Code Playgroud)
所以只需更改:
checksum = hashlib.md5(open(path).read())
Run Code Online (Sandbox Code Playgroud)
至
checksum = hashlib.md5(open(path).read()).hexdigest()
Run Code Online (Sandbox Code Playgroud)