【问题标题】:Frequently check a file while subprocess is writing to it子进程写入文件时经常检查文件
【发布时间】:2022-01-20 04:52:36
【问题描述】:

我有以下代码,其中 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 启动run.out 并捕获其输出。 Popen 特别允许您在生成标准输出时读取它。
  • 子进程运行时读取storage.txt是什么意思?
  • @kalatabe 我知道拥有stdout=subprocess .PIPE 要容易得多,但出于几个原因,我必须写入文件。
  • 注意,写入文件(或管道)通常在操作系统级别缓冲。您可能必须先写几个 ko 才能在文件中看到任何内容...
  • @MauriceMeyer 确切地说,当子进程正在写入它时,我想读取文件。

标签: python subprocess


【解决方案1】:

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

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 ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多