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() 我必须一次输入一个命令,但假设我可以输入多个命令,如下所示:

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

我如何让它同时运行,即使它实际上会执行“urbandictionary hello”然后“reverse hello”第二我听说 thready 可以做到这一点,但我不确定我将如何使用线程来做到这一点。即使我先做了“urbandictionary hello”,在它返回 hello 的城市字典结果之前,线程是否是让它实际发布“olleh”的唯一选择?

4

1 回答 1

1

你需要一份工作Queuethreading模块。

这是一个启发您并帮助您入门的示例:

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 回答