我有一个 python 脚本,它在 Windows 系统上使用 msbuild 构建一个解决方案文件。我想在构建过程运行时显示命令提示符输出。我的代码如下所示
def build(self,projpath):
if not os.path.isfile(self.msbuild):
raise Exception('MSBuild.exe not found. path=' + self.msbuild)
arg1 = '/t:Rebuild'
arg2 = '/p:Configuration=Release'
p = subprocess.call([self.msbuild,projpath,arg1,arg2])
print p
if p==1:
return False
return True
我能够构建文件,但我需要在单独的 GUI(状态窗口)中显示构建状态。我尝试了很多将命令提示符输出重定向到文件,然后从文件中读取,但是,可以没成功。 我尝试使用以下命令,
subprocess.check_output('subprocess.call([self.msbuild,projpath,arg1,arg2])', shell=False) > 'C:\tmp\file.txt'
谁能告诉我当我运行脚本时如何在状态窗口(使用 wxpython 的 GUI)中显示命令提示符的所有输出?
最佳答案
当我想用wxPython捕获traceroute和ping命令时,我做了类似的事情。我在本教程中写过:http://www.blog.pythonlibrary.org/2010/06/05/python-running-ping-traceroute-and-more/
首先,您需要 redirect stdout ,基本上是这样的:
redir=RedirectText(log)
sys.stdout=redir
其中RedirectText是一个特殊的类,它接受wx.TextCtrl作为参数。见下文:
class RedirectText(object):
def __init__(self,aWxTextCtrl):
self.out=aWxTextCtrl
def write(self,string):
self.out.WriteText(string)
这是我的 ping 命令的示例:
proc = subprocess.Popen("ping %s" % ip, shell=True,
stdout=subprocess.PIPE)
print
while True:
line = proc.stdout.readline()
wx.Yield()
if line.strip() == "":
pass
else:
print line.strip()
if not line: break
proc.wait()
所以你只需要运行 subprocess 并使用它的 readline 函数来获取输出的数据。然后将输出打印到 stdout,该输出被重定向到文本控件。 wx.Yield() 调用将允许文本控件实时更新。否则,它将在子流程完成后更新。
关于python-2.7 - 在 python 中的单独窗口中读取命令提示符输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15198967/