長時間実行しているシェルスクリプトは、stdoutとstderrを生成します。これはGUIのtextctrlに表示します。これは、GUIスレッドをシェルスクリプトのスレッドから分離して分離することによって可能です。しかし、私がマルチプロセッシングを実装するとき、私はロードブロッキングを打ちました。ここに私のダウンストリッピングされたコード:wxPython TextCtrlの別のプロセスで実行されているシェルスクリプトの出力をキャプチャするにはどうすればよいですか?
#!/usr/bin/env python
import wx
import sys, subprocess
from multiprocessing import Process, Queue
from Queue import Empty
class MyFrame(wx.Frame):
def __init__(self, *args, **kwds):
wx.Frame.__init__(self, *args, **kwds)
self.button = wx.Button(self, -1 , "Run")
self.output = wx.TextCtrl(self, -1, '', style=wx.TE_MULTILINE|\
wx.TE_READONLY|wx.HSCROLL)
self.Bind(wx.EVT_BUTTON, self.OnButton, self.button)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.output, -1, wx.EXPAND, 0)
sizer.Add(self.button)
self.SetSizerAndFit(sizer)
self.Centre()
def OnButton(self, event):
numtasks = 4 # total number of tasks to run
numprocs = 2 # number of processors = number of parallel tasks
work_queue = Queue()
for i in xrange(numtasks):
work_queue.put(i)
processes = [Process(target=self.doWork, args=(work_queue,))
for i in range(numprocs)]
for p in processes:
p.daemon = True
p.start()
def doWork(self, work_queue):
while True:
try:
x = work_queue.get(block=False)
self.runScript(x)
except Empty:
print "Queue Empty"
break
def runScript(self, taskno):
print '## Now Running: ', taskno
command = ['./script.sh']
proc = subprocess.Popen(command, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
while True:
stdout = proc.stdout.readline()
if not stdout:
break
#sys.stdout.flush() #no need for flush, apparently it is embedded in the multiprocessing module
self.output.AppendText(stdout.rstrip()) #this is the part that doesn't work.
if __name__ == "__main__":
app = wx.App(0)
frame = MyFrame(None, title="shell2textctrl", size=(500,500))
frame.Show(True)
app.MainLoop()
私は他人の提案に多くの解決策を試した。その中には、GUIを応答させるためにwx.CallAfterまたはwx.lib.delayedresultを使用する方法、いくつかのスレッドレシピ(例えば、wxApplication Development Cookbook、threadpool、others ...)と、別のスレッドから実行されるmultiprocess() text.rlに書き込むためにsys.stdout.writeを再定義します。それ以外のものはありません。いずれも成功しなかった。誰でも作業コードと一緒にソリューションを提供してもらえますか?
#!/bin/tcsh -f
@ i = 1
while ($i <= 20)
echo $i
@ i += 1
sleep 0.2
end
確かに、私はLongRunningProcessの記事とあなたのチュートリアル(非常に便利です!)を見ました。私は_threading_で動作するように自分のコードを取得できますが、_multiprocessing_では動作しません。マルチスレッドはスレッド化に基づいているため、愚かです。そして、これらの2つのモジュールがどのように機能するかについての私の理解は、厳しく制限されています。残念ながら、私は本当にマルチプロセッシングを使用する必要があります。 –
私はまだマルチプロセッシングを使用していないので、その時点ではコメントできません。私が時間を見つけたら、それを掘り下げます。 –