在其中一个命令已在运行时执行

时间:2013-10-29 23:45:13

标签: python

正如标题所述,在处理一个命令时,我将如何执行其他命令? 让我们假设我有这个:

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”然后“反向问候”第二我听说已经可以做到这一点但是我不确定如何使用线程来做到这一点。尽管我首先做了“urbandictionary你好”,但是在它返回城市词典结果之前它是否真正发布“olleh”的唯一选项?

1 个答案:

答案 0 :(得分: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