サブプロセスを実行する
subprocessクラスを使って、プログラムの中で別のプロセスを起動する。
以下のコードで正常に動作することを確認した。
import subprocess import sys, time itime=0 cmd = "python cmdtest.py" p=subprocess.Popen(cmd, stdout=subprocess.PIPE) while (p.poll()==None): itime +=1 sys.stdout.write('.') time.sleep(0.2) print "completed" print p.stdout.read() # display results of cmdtest
Popenメソッドの引数の"stdout=subprocess.PIPE"で、サブプロセスと親の間のパイプを作る。
p.poll()でサブプロセスの終了を確認する(Noneは未終了)。
p.stdout.read()でサブプロセスからの出力を表示する。
メモ(simple.py)
サンプルコードの中に、基本的なwxPythonコード例(simple.py)を見つける。
wx.Frame, wx.Panel, wx.StaticText, wx.Button, wx.BoxSizerの使い方を勉強するのにいいかもしれないので、ここにメモしておく。
C:\Program Files\wxPython2.8 Docs and Demos\samples\simple
メニューから"Dummy1"を選ぶと、ファイルsimple.pyの内容を現在のウィンドウ上に表示する
ウィンドウにメニュー項目を作ることは容易。項目の中に、Dummy1とExitを用意し、Exitを選ぶとウィンドウを閉じ、Dummy1を選ぶとテキストファイルの内容を現在のウィンドウ上に表示するようにしたい。
そこで以下の"proto1.py"を作成した。
import wx class MyFrame(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, -1, title, pos=(150,150), size=(650,400)) menuBar = wx.MenuBar() menu = wx.Menu() menu.Append(101, "&Dummy 1", "This is dummy menu1.") menu.AppendSeparator() menu.Append(103, "&Exit\tAlt-X", "Exit this sample") self.Bind(wx.EVT_MENU, self.DummyAction1, id=101) self.Bind(wx.EVT_MENU, self.OnTimeToClose, id=103) menuBar.Append(menu, "&File") self.SetMenuBar(menuBar) self.CreateStatusBar() self.panel = wx.Panel(self) # making a panel on window def OnTimeToClose(self, evt): self.Close() def DummyAction1(self, evt): f = open("simple.py", "r") msg = f.read() f.close() tc = wx.TextCtrl(self.panel, -1, msg, style=wx.TE_MULTILINE) class MyApp(wx.App): def OnInit(self): frame = MyFrame(None, "Simple GUI") # self.SetTopWindow(frame) print "Starting this sample GUI" frame.Show() return True app = MyApp(redirect=False) app.MainLoop()
wx.TextCtrlでファイルの内容を表示するようにしているのであるが、結果は写真のように隅の方に表示されてしまう。ウィンドウをいっぱいに使って全面で表示したいのであるが、うまくいかないなあ。
参考になりそうなものをデモで探してみることにする。