Python子进程执行的脚本不会写入文件

问题描述:

我写了两个脚本,其中一个脚本调用subprocess.Popen运行终端命令以执行第二个脚本.等待5秒钟后,它将终止子进程.

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.

在子过程中,我有一个while循环轮询一个寄存器并将该寄存器的内容写入文件.

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

我使用的方法是

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

每当我独立运行while循环运行脚本时,它将寄存器的内容写入文件.但是,当我执行主脚本并将轮询脚本作为子进程执行时,终止后它不会写入文件.

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?

在文件打开时使用上下文,并在睡眠之前添加刷新:

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)