私はマルチスレッドのpythonスクリプトに取り組んでおり、新しいzshシェルを再度開くことなく、同じセッションを維持しながら、いくつかのシェルコマンドを実行する専用スレッドを持っています。
メインスレッドは、コマンドの実行を担当するスレッドと共有されるキューに、実行されるコマンドを入れます。
import threading, Queue
class ShellThread(threading.Thread):
def __init__(self, command_q, command_e):
super(ShellThread, self).__init__()
self.command_q = command_q
self.command_e = command_e
self.stoprequest = threading.Event()
from subprocess import Popen, PIPE
import os
self.zsh = Popen("zsh", stdin=PIPE, stdout=PIPE)
def run(self):
while not self.stoprequest.isSet():
try:
command = self.command_q.get(True, 0.1)
print "ShellThread is now executing command : " + command
self.zsh.stdin.write(command + '\n')
self.zsh.stdin.flush()
self.command_e.set()
except Queue.Empty:
continue
def join(self, timeout=None):
self.stoprequest.set()
self.zsh.stdin.close()
super(ShellThread, self).join(timeout)
def main(args):
__command_q = Queue.Queue()
__command_e = threading.Event()
__thread = ShellThread(command_q=__command_q, command_e=__command_e)
__thread.start()
while 1:
line = raw_input()
print 'MainThread : ' + line
__command_q.put(line)
__command_e.wait(0.5)
__command_e.clear()
if __name__ == '__main__':
import sys
main(sys.argv[1:])
それは機能しますが、ランダムなエラーが発生し、各コマンドを実行IOError: [Errno 32] Broken pipe
した後に取得する方法がまだ見つかりません。stdout
更新:
これの全体的なポイントは、1 つだけの zsh シェルを開いたままにしておくことであることに注意してください (これが、この目的のために専用のスレッドを用意している理由です)。Popen.communicate
コマンドが終了するとシェルが閉じられ、前もって実行する必要があるすべてのコマンドがわからないため、使用できません。