简体   繁体   English

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

[英]Python subprocess executed script wont write to file

I have written two scripts where one script calls subprocess.Popen to run a terminal command to execute the second script. 我编写了两个脚本,其中一个脚本调用subprocess.Popen运行终端命令以执行第二个脚本。 After waiting 5 seconds, it will terminate the subprocess. 等待5秒钟后,它将终止子进程。

In the subprocess, I have a while loop polling a register and writing the contents of that register to a file. 在子过程中,我有一个while循环轮询一个寄存器,并将该寄存器的内容写入文件。

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. 每当我单独运行while循环运行脚本时,它会将寄存器的内容写入文件。 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)

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. 尝试调用f.flush()以确保将输出写入文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM