2013-10-29 41 views
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 

我将如何得到它同时运行,即使它实际上做“城市词典你好”,然后“反向你好”第二听说纤维性能做到这一点,但我不知道我怎么会那样做与线程。是否有线程唯一的选择,让它实际上发布“olleh”,然后它将返回城市字典结果作为hello,即使我先执行了“urbandictionary hello”?

+0

你需要[主题](http://docs.python.org/2/library/thread.html)■! – 2013-10-29 23:49:19

+1

'线程'。你也来自java背景?你不需要一个班级去做所有事情,当然不是上述事情。 – roippi

+0

你不需要线程。你可以使用Twisted,grequests,甚至子进程。它看起来像你在Python 3,所以你也可以给asyncio一个旋风。 – Eevee

回答

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