如何在使用Python代码终止应用程序时重定向错误消息?

2024-05-16 10:12:28 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

内部控制PC_清洁.py公司名称:

^{pr2}$

运行脚本后,我发现成功消息被写入清理.txt公司名称:

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

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

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

有什么建议如何将错误消息重定向到(最好)同一个文本文件?在


Tags: thepytxt脚本名称应用程序消息错误
2条回答

多亏了阿摩。这是捕获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)

使用子流程.popen. 它可以定义cmd的stdin/stdout/stderr。 希望这对你有帮助

相关问题 更多 >