打印到文件的多个子进程

Multiple Subprocesses Printing to File

我目前在使用两个子进程(修复此问题后我会添加更多)打印到文件时遇到问题。我从 awk 得到总和,现在我试图将它打印到一个文件中,但打印不正确。我使用的是 Python 2.6,无法升级。我也在程序结束时关闭我的文件,所以这不是问题。 编辑: 这段代码的目的是遍历文件并计算特定字符串出现的次数。将它们放在文件中,然后在最终输出文件中汇总文件。

def serv2Process(HOST = "testServer.com"):
        encInTotal1 = 0
        signInTotal1 = 0
        p = subprocess.Popen(["ssh", "%s" % HOST, COMMAND],
            shell = False,
            stdout = subprocess.PIPE,
            close_fds = True)
        for line in p.stdout:
            if 'String to search'.lower() in line.lower():
                totalCount1 = totalCount1 +1
            if 'String 2 to search'.lower() in line.lower():
                totalCount2 = totalCount2 +1
        file1.write("%s\n" %totalCount1)
        file2.write("%s\n" %totalCount2)

        sys.stdout.flush()

    p1 =threading.Thread(target = serv1Process, args=(HOST1,), name = 'serv1Process')
    p2=threading.Thread(target = serv2Process, args= (HOST2,), name = 'serv2Process')
    p1.start()
    p2.start()
    p1.join()
    p2.join()
    with open("SomeScriptName.%s" % strDateForm, 'w+')as search_file:
        search_file.write("Header: ")
        sys.stdout.flush()
        proc = subprocess.Popen(['awk', '{sum+=} END {print sum}',"file1.%s" %strDateForm], shell=False, stdout=search_file,close_fds = True)
        proc.wait()

        search_file.write("\n")
        search_file.write("Header2: ")
        search_file.flush()
        proc2 = subprocess.Popen(['awk', '{s+=} END {print s}',"file2.%s" %strDateForm], shell=False, stdout=search_file,close_fds = True)
        proc2.wait()
    file1.close()
    file2.close()

您需要确保您没有在启动进程的同时写入文件。为此,请确保在启动进程之前刷新文件,并在再次写入之前等待进程完成。

with open("SomeFileName.%s" % strDateForm, 'w+') as search_file:

    search_file.write("header: ")
    search_file.flush()

    proc = subprocess.Popen(['awk', '{sum+=} END {print sum}',"AnotherFileName" ], shell=False, stdout=search_file,stderr = subprocess.PIPE,close_fds = True)
    proc.wait()

    search_file.write("Header 2: ")
    search_file.flush()

    proc2 = subprocess.Popen(['awk', '{s+=} END {print s}',"AThirdFileName"], shell=False, stdout=search_file,stderr = subprocess.PIPE,close_fds = True)
    proc2.wait()

您也将 stderr 重定向到一个管道,但您从未从中读取过。如果子进程在 stderr 上产生足够的输出来填充管道缓冲区,它将阻塞。如果您对 stderr 不感兴趣,要么不要将其重定向到终端,要么将其重定向到 /dev/null.

并且您尝试刷新 sys.stdout,但这不会真正影响与此代码相关的任何内容。


编辑:在看到你更新的代码后,一些评论:

  • 假设打开的文件 file1file2awk 子进程尝试读取的文件:确保在 [=36] 之前刷新或关闭它们=] 启动任何进程。
  • 您多次调用 sys.stdout.flush(),但这样做没有意义。你并不是真的在写 sys.stdoutd,所以刷新它并没有真正做任何事情。刷新 file1file2search_file
  • 如果这不是练习使用 subprocess 模块的代码,您可能应该考虑直接使用 python 来对文件中的数字求和,而不是向 awk 求和。