多个子进程打印到文件



我目前在使用两个子流程(修复后我会添加更多)打印到文件时遇到问题。我从awk那里得到了总数,现在我正试图将其打印到一个文件中,但打印不正确。我使用的是Python2.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("%sn" %totalCount1)
file2.write("%sn" %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+=$1} 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+=$1} 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+=$1} 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+=$1} 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子进程尝试读取的文件:请确保在启动任何进程之前刷新或关闭它们
  • 您多次呼叫sys.stdout.flush(),但这样做毫无意义。您实际上并不是在写sys.stdoutd,所以刷新它并没有真正起到任何作用。而是刷新file1file2search_file
  • 如果这不是使用subprocess模块的代码,那么您可能应该考虑直接使用python来总结文件中的数字,而不是使用awk

最新更新