在子进程写入文件时经常检查文件

Frequently check a file while subprocess is writing to it

我有以下代码,其中 c++ 可执行文件 (run.out) 使用 std::cout 在运行时打印出一堆信息。此代码将 run.out 的输出存储到 storage.txt.

storage = open("storage.txt", "w")
shell_cmd = "run.out" 
proc = subprocess.Popen([shell_cmd], stdout=storage, stderr=storage)

一旦subprocess开始,我需要经常检查storage.txt的内容,并根据那里刚刚存储的内容来决定。我该怎么做?

您可以立即使用 subprocess.poll() which returns 并指示子进程是否仍然 运行:

while proc.poll() is None:
    time.sleep(0.25)  # reads the content 4 times a seconds!
    data = open("storage.txt").read()
    if 'error' in data:
        print("failed ...")
        # somesomething ...