The .js file is written out by my python script which does a bunch of other stuff too. This all actually works exactly as I want it to, and the values that get written to the file are accurate and do appear correctly on the gauge if I run it as a single loop and not in a continuous "monitoring service" mode where it runs until interrupted.
Here's where the issue starts I think: the loop that measures sound levels runs ~ 30k times in 5 seconds. In my python code I use:
with open(web_file, 'w') as f_output:
f_output.write("var int_level = " + str(per_detected))
.close() is definitely not needed. At issue is your browser reading the file while it is still open anyway and finding it in a truncated (so empty) state from time to time. And you can never close the file fast enough to prevent this.
What you should do instead is write the file to a different filename, then rename the file to replace the old file. This is an atomic operation (meaning the Operating System guarantees that any other access to the file will either get the old, or the new file, but never just a part of both).
This is as simple as:
with open(web_file + '.new', 'w') as f_output: f_output.write("var int_level = " + str(per_detected)) os.rename(web_file + '.new', web_file)
The above code writes out to a different filename, one ending in
.new, and only when writing has completed (and the file is closed), is it moved into place to replace the old version of the file.