'Load new values from another Python script
I have a device which I am controlling in a for loop. I would like to check every iteration if a .txt file has changed. If it has I want to read values and send them to the device. I am checking if file was updated like this:
os.stat("myfile.txt").stat.st_mtime
This is working fine when I manually open file, write values and save file.
I want to change values by another Python script which will be run by another process. In this other script I write values to the .txt file like this:
text_file = open("myfile.txt", 'w')
text_file.write("\n0\n0\n0")
text_file.close()
When I call open(), st_mtime changes and I load nothing because text file is empty. How to deal with this? Are there other approaches besides a text file to set new values by another Python process?
Solution 1:[1]
I used 3 files. I check if 3th files st_mtime has changed. I write new values to a second file, and than open and close 3th file. St_mtime of the 3th file changes so i load values from second file safely. :)
Solution 2:[2]
You could try an alternate way to check if the contents have changed, by checking for MD5 checksum for example.
import hashlib
..
my_hex = hashlib.md5(text_file.read()).hexdigest()
You can now monitor my_hex every iteration to check if your file contents have changed.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Pan Zemiak |
| Solution 2 | alexverus |
