외부 프로그램을 실행하고 그 표준 출력/에러를 텍스트 컨트롤에 표시하는 어플의 Template입니다.


template2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# -*- coding: utf-8 -*-
#!/usr/bin/python
  
import wx
import subprocess
import threading
import sys
  
COMMAND_PATH = "test.py" # 실행할 외부 프로그램 경로
 
def stdout_thread(pipe, callback):
    for line in iter(pipe.stdout.readline, b''):
        callback(line.rstrip())
 
def exec_command(cmd, callback, cwd=None):
    p = subprocess.Popen(cmd,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.STDOUT, cwd=cwd)
    out_thread = threading.Thread(name='stdout_thread', target=stdout_thread, args=(p, callback))
 
    out_thread.start()
  
class MainWindow(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size = (480, 320),
            style = wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE)
              
        vbox = wx.BoxSizer(wx.VERTICAL)
 
        self.tc = wx.TextCtrl(self, 1, size = (-1, 200), style = wx.TE_MULTILINE)
        vbox.Add(self.tc, 0, wx.EXPAND | wx.ALL)
 
        self.SetSizer(vbox, True)
        self.Layout()
          
def callback_stdout(msg):
    print("}}} " + msg)
    frame.tc.AppendText(msg + "\n")
              
app = wx.App(False)
frame = MainWindow(None, -1, u"Title")
frame.Show(1)
 
exec_command([sys.executable, COMMAND_PATH], callback_stdout)
 
app.MainLoop()


test.py
1
2
3
4
5
6
7
# -*- coding: utf-8 -*-
#!/usr/bin/python
 
import sys
 
print "blah;blah;"
sys.stdout.flush()


[주의사항] 실행하려는 외부 프로그램이 python 코드일 때, 외부 프로그램에서 메세지 출력 후 sys.stdout.flush()를 해줘야 메세지가 그때 그때 출력된다. 그렇지 않으면 메세지가 마지막에 한꺼번에 출력된다.


template2.py 실행 화면


 


<테스트 환경>
OS : Windows 7
Python 버전 : 2.7
wxPython 버전 : 2.8.12.1


,