Reputation: 127
I want my program to wait until a specific file will contain text instead of empty string. Another program writes data to the file. When I run the first program my computer starts overheating because of the while loop that continously checks the file content. What can I do instead of that loop?
Upvotes: 1
Views: 248
Reputation: 4633
A better solution would be to start that process from within your Python script:
from subprocess import call
retcode = call(['myprocess', 'arg1', 'arg2', 'argN'])
Check if retcode
is zero, this means success--your process ran successfully with no problems. You could also use os.system
instead of subprocess.call
. Once the process is finished, you would know now you can read the file.
Why this method is better than monitoring files?
The process might fail and there might be no output in the file you're trying to read from. In this case scenario, your process will check the file again and again, looking for data, this wastes kernel I/O operation time. There's nothing that could guarantee that the process will succeed at all times.
The process may receive signals, (i,e. STOP
and CONT
), if the process received the STOP
signal, the kernel will stop the process and there might be nothing that you could read from the output file, especially if you intend to read all the data at once like when you're sorting a file. Once the process receives CONT signal, there the process will start again. Basically, this means your Python script will be trying to read simultaneously from the file while the process is stopped.
The disadvantage of this method is that, the process needs to finish first before your Python script process the output from the file. The subprocess.call
blocks, the next line won't be executed by Python interpreter until the spawned process finishes first, you could instead use subprocess.Popen
which is non-blocking. Even better and if possible, redirect the output of the process to stdout and use Popen
to read the output of your process from its stdout and then write the output from the Python script to a file.
Upvotes: 1