无法运行子进程并将输出重定向到日志文件

时间:2015-03-16 07:15:57

标签: python python-2.7 python-3.x

以下代码不会写入我正在创建的日志文件(Dm_Log.txt)。但是如果我注释掉stdout,那么stderr = process.communicate()就可以了。如果我不使用通信,那么子进程会停止,因为我正在进行process.wait()。怎么解决这个?我需要在日志文件中写入并运行该过程。

  logfilePath = self.psexeclogs + 'Dm_Log.txt'
  logfile = file(logfilePath,'w')

  try:

   process = subprocess.Popen(drivemaster_open_command, stdout = subprocess.PIPE,stderr = subprocess.PIPE)
   stdout, stderr = process.communicate()

   for line in process.stderr:
    print ' '
    sys.stderr.write(line)
    logfile.write(line)
   process.wait()

  except OSError:
    print "********COULD NOT FIND PSEXEC.EXE, PLEASE REINSTALL AND SET THE PATH VARIABLE PROPERLY********\n"

  #Close the logfile first
  logfile.close()

1 个答案:

答案 0 :(得分:0)

使用communicate 等待流程终止后,您就无法使用process.stderr而只能使用stderr

  

Popen.communicate(input=None)

     

与流程交互:将数据发送到stdin。从stdout和stderr读取数据,直到达到文件结尾。等待进程终止

for line in stderr:
   print ' '
   sys.stderr.write(line)
   logfile.write(line)
相关问题