简体   繁体   English

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

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

I am running a python script through a batch file. 我正在通过批处理文件运行python脚本。 In the python code I am basically closing different applications already running on the computer before proceeding with a new test run. 在执行新的测试运行之前,我基本上是在python代码中关闭计算机上已经运行的不同应用程序。 I need to parse the output log that no applications are open and then only proceed. 我需要解析没有打开任何应用程序的输出日志,然后仅继续进行。 To capture the command prompt I am redirecting the output as below: 为了捕获命令提示符,我将输出重定向如下:

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

Inside controlpc_clean.py: 在controlpc_clean.py内部:

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

After running the script I find that SUCCESS messages are getting written in cleanup.txt: 运行脚本后,我发现成功消息正在cleanup.txt中写入:

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

But, if xt-ocd application is already closed, then the error message comes in the command prompt but does not get written in cleanup.txt: 但是,如果xt-ocd应用程序已经关闭,则错误消息会出现在命令提示符下,但不会写入cleanup.txt中:

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

Any suggestions how to redirect the error message to (preferably) the same text file ? 任何建议如何将错误消息重定向到(最好是)同一文本文件?

Use subprocess.popen. 使用subprocess.popen。 it can define the stdin/stdout/stderr of your cmd. 它可以定义您的cmd的stdin / stdout / stderr。 Wish this could help you 希望这对您有帮助

Thanks to amow. 多亏了amow。 This is the code which captures both stderr as well as stdout: 这是捕获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