简体   繁体   中英

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

I am running a python script through a batch file. In the python code I am basically closing different applications already running on the computer before proceeding with a new test run. 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:

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

After running the script I find that SUCCESS messages are getting written in 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:

"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. it can define the stdin/stdout/stderr of your cmd. Wish this could help you

Thanks to amow. This is the code which captures both stderr as well as 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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