1

タイトルが示すように、あるコマンドが既に処理されている間に他のコマンドを実行するにはどうすればよいですか? 仮に私がこれを持っているとしましょう:

import urllib.request
import re
class runCommands:
      def say(self,word):
          return word
      def rsay(self,word):
          return word[::-1]
      def urban(self,term):
          data = urllib.request.urlopen("http://urbandictionary.com/define.php?term=%s" % term).read().decode()
          definition = re.search('<div class="definition">(.*?)</div>',data).group(1)
          return definition
      def run(self):
          while True:
                command = input("Command: ")
                command,data = command.split(" ",1)
                if command == "say": print(self.say(data))
                if command == "reversesay": print(self.rsay(data))
                if command == "urbandictionary": print(self.urban(data))

今、runCommands().run() を実行すると、一度に 1 つずつコマンドを入力する必要があることがわかりましたが、次のように複数のコマンドを入力する方法があれば、仮説としては次のようになります。

 me: "urbandictionary hello"
 me: "reverse hello" # before it posts the result

実際には「urbandictionary hello」を実行してから「reverse hello」を実行するにもかかわらず、両方を同時に実行するにはどうすればよいでしょうか。最初に「urbandictionary hello」を実行したにもかかわらず、hello の都市辞書の結果を返す前に、実際に「olleh」を投稿する唯一のオプションはスレッド化ですか?

4

1 に答える 1

1

Queueジョブとthreadingモジュール が必要です。

以下は、インスピレーションを与えて開始するための例です。

from Queue import Queue
from threading import Thread

def worker():
    while True:
        item = q.get()
        do_work(item)
        q.task_done()

q = Queue()
for i in range(num_worker_threads):
     t = Thread(target=worker)
     t.daemon = True
     t.start()

for item in source():
    q.put(item)

q.join()       # block until all tasks are done
于 2013-10-29T23:48:55.957 に答える