Python subprocess executed script wont write to fi

2019-07-31 07:02发布

问题:

I have written two scripts where one script calls subprocess.Popen to run a terminal command to execute the second script. After waiting 5 seconds, it will terminate the subprocess.

In the subprocess, I have a while loop polling a register and writing the contents of that register to a file.

The method I am using is

f = open(filename, 'w')
...
while 1:
    *poll register*
    f.write(fp0)
    sleep(1)

Whenever I run the script with the while loop stand alone, it writes the contents of the register to the file. However, when i execute the main script and execute the polling script as a subprocess, it does not write to the file after it terminates.

Can anyone provide any suggestions to the problem?

回答1:

Use a context on the opening of the file, and add a flush right before you sleep:

with open(filename, 'w') as f:
    ...
    while 1:
        *poll register*
        f.write(fp0)
        f.flush()
        sleep(1)


回答2:

Since you are terminating the sub-process maybe it is not flushing the output to the file. Try calling f.flush() to make sure the output is written to file.