问题
Developed a script which builds a project using msbuild. I have GUI developed using wxpython which has a button on which when user clicks would build a project using msbuild. Now, i want to open a status window when user click on that button and shows all the output which shows in the command prompt and command prompt should not be displayed i.e,redirecting the command prompt output to the user GUI status window. My build script is,
def build(self,projpath)
arg1 = '/t:Rebuild'
arg2 = '/p:Configuration=Release'
arg3 = '/p:Platform=x86'
p = subprocess.call([self.msbuild,projpath,arg1,arg2,arg3])
if p==1:
return False
return True
回答1:
I actually wrote about this a few years ago on my blog where I created a script to redirect ping and traceroute to my wxPython app: http://www.blog.pythonlibrary.org/2010/06/05/python-running-ping-traceroute-and-more/
Basically you create a simple class to redirect stdout to and pass it an instance of a TextCtrl. It ends up looking something like this:
class RedirectText:
def __init__(self,aWxTextCtrl):
self.out=aWxTextCtrl
def write(self,string):
self.out.WriteText(string)
Then when I wrote my ping command, I did this:
def pingIP(self, ip):
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()
The main thing to look at is the stdout parameter in your subprocess call and the wx.Yield() is important too. The Yield allows the text to get "printed" (i.e. redirected) to stdout. Without it, the text won't show up until the command is finished. I hope that all made sense.
回答2:
I made a change like below,it did work for me.
def build(self,projpath):
arg1 = '/t:Rebuild'
arg2 = '/p:Configuration=Release'
arg3 = '/p:Platform=Win32'
proc = subprocess.Popen(([self.msbuild,projpath,arg1,arg2,arg3]), 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()
来源:https://stackoverflow.com/questions/15471007/redirect-command-prompt-output-to-a-python-generated-window