Python子进程执行的脚本不会写入文件 [英] Python subprocess executed script wont write to file

查看:54
本文介绍了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)

这篇关于Python子进程执行的脚本不会写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆