繁体   English   中英

使用Python代码杀死应用程序时如何重定向错误消息?

[英]How to redirect error message while killing an application using Python code?

我正在通过批处理文件运行python脚本。 在执行新的测试运行之前,我基本上是在python代码中关闭计算机上已经运行的不同应用程序。 我需要解析没有打开任何应用程序的输出日志,然后仅继续进行。 为了捕获命令提示符,我将输出重定向如下:

 python C:\controlpc_clean.py > output.log 2 > C:\cleanup.txt"

在controlpc_clean.py内部:

os.system("TASKKILL /F /IM xt-ocd.exe") 

运行脚本后,我发现成功消息正在cleanup.txt中写入:

"SUCCESS: The process "xt-ocd.exe" with PID 3052 has been terminated."

但是,如果xt-ocd应用程序已经关闭,则错误消息会出现在命令提示符下,但不会写入cleanup.txt中:

"ERROR: The process "xt-ocd.exe" not found." \\Only gets displayed in command prompt

任何建议如何将错误消息重定向到(最好是)同一文本文件?

使用subprocess.popen。 它可以定义您的cmd的stdin / stdout / stderr。 希望这对您有帮助

多亏了amow。 这是捕获stderr和stdout的代码:

try:

  ocdclose_command =  "TASKKILL /F /IM xt-ocd.exe"
  process = subprocess.Popen(ocdclose_command, stdout = subprocess.PIPE,stderr = subprocess.PIPE)


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

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

  process.wait()

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

time.sleep(2)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM