2017年4月25日 星期二

[ Python 常見問題 ] Saving stdout from subprocess.Popen to file

Source From Here
Question
I'm writing a Python script that uses subprocess.Popen to execute two programs (from compiled C code) which each produce stdout. The script gets that output and saves it to a file. Because the output is sometimes large enough to overwhelm subprocess.PIPE, causing the script to hang, I send the stdout directly to the log file. I want to have my script write something to the beginning and end of the file, and between the two subprocess.PIPE calls. However, when I look at my log file, anything I wrote to the log file from the script is all together at the top of the file, followed by all the executable stdout. How can I interleave my added text to the file?
  1. def run(cmd, logfile):  
  2.     p = subprocess.Popen(cmd, shell=True, universal_newlines=True, stdout=logfile)  
  3.     return p  
  4.   
  5. def runTest(path, flags, name):  
  6.     log = open(name, "w")  
  7.     print >> log, "Calling executable A"  
  8.     a_ret = run(path + "executable_a_name" + flags, log)  
  9.     print >> log, "Calling executable B"  
  10.     b_ret = run(path + "executable_b_name" + flags, log)  
  11.     print >> log, "More stuff"  
  12.     log.close()  
How-To
You could call .wait() on each Popen object in order to be sure that it's finished and then call log.flush(). Maybe something like this:
  1. def run(cmd, logfile):  
  2.     p = subprocess.Popen(cmd, shell=True, universal_newlines=True, stdout=logfile)  
  3.     ret_code = p.wait()  
  4.     logfile.flush()  
  5.     return ret_code  
Supplement
How do I redirect stdout to a file when using subprocess.call in python?
  1. with open('out-file.txt''w') as f:  
  2.     subprocess.call(['program'], stdout=f)  


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...