当我使用pythonw.exe在窗口上运行以下脚本时,我希望能够获取stdout和stderr的内容:
import subprocess
import sys
import os
import string
import time
tmpdir = 'c:/temp'
cmd = 'dir c:'
tmpfile = "tmp_%f" % (time.time())
tmpfile = os.path.normpath(os.path.join(tmpdir,tmpfile))
tmpfile2 = tmpfile+".bat"
tmpfile3 = tmpfile+".txt"
fa = open(tmpfile2,'w')
fa.write("@ECHO OFF > NUL\n")
fa.write('call '+cmd+"\n")
fa.close()
wcmd = []
wcmd.append(tmpfile2)
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW
fb = open(tmpfile3,'w')
fb.write("\n")
fb.write(tmpfile2+"\n")
try:
procval = subprocess.Popen(wcmd, startupinfo=startupinfo, stdout=subprocess.PIPE, stderr=subprocess.STDOUT).communicate()
fb.write(str(procval)+"\n")
fb.write("Sucess")
fb.close()
except:
fb.write(str(procval)+"\n")
fb.write("Failure")
fb.close()当我使用python.exe执行它时,我得到了预期的输出结果。当我使用pythonw.exe运行它
我最终在异常方面。如果我只用命令和startupinfo标志运行popen命令将成功完成,但不能访问子进程中的数据。我读过的所有内容都表明这应该起作用,但必须缺少一些东西。任何帮助将不胜感激。
谢谢,
兰迪