Suppose I have a program A. I run it, and performs some operation starting from a file foo.txt. Now A terminates.
New run of A. It checks if the file foo.txt has changed. If the file has changed, A runs its operation again, otherwise, it quits.
Does a library function/external library for this exists ?
Of course it can be implemented with an md5 + a file/db containing the md5. I want to prevent reinventing the wheel.
Autoreload is a simple python script to watch a directory for changed files and restarts a process when the change is detected. For instance, I run ./autoreload python main.py. This first runs python main.py, then watches the current working directory and all subdirectories for changes.
In Python, you can check whether certain files or directories exist using the isfile() and isdir() methods, respectively. However, if you use isfile() to check if a certain directory exists, the method will return False . Likewise, if you use if isdir() to check whether a certain file exists, the method returns False .
FYI - for those using this example who got this error: "TypeError: can't pickle HASH objects" Simply modify the following (optionally update md5 to hashlib, md5 is deprecated):
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"))
so just change:
checksum = hashlib.md5(open(path).read())
to
checksum = hashlib.md5(open(path).read()).hexdigest()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With