2013-10-29 4 views
1

제목이 표시 될 때 이미 하나가 처리되는 동안 다른 명령을 어떻게 실행합니까? 내가이 가상으로 말할 수 있습니다 :. 내가 runCommands을하는 것을 깨닫게 지금이미 실행 중일 때 다른 명령을 실행하십시오.

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)) 

()를 한 번에 하나의 명령 만 가정 해 만약 내가 입력이) (실행 I 수 같은 몇 가지 방법 입력 다중 명령 :

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

나는 그것이 실제로 "안녕하세요 어번 딕셔너리"다음 "안녕하세요 반전"두 번째 난 할 수 실상 들었하지만 난 그렇게 할 것입니다 얼마나 확실하지 않다 할 것입니다 비록 동시에 실행하는 방법을 얻을 것입니다 스레딩. 먼저 "urbandictionary hello"를 했더라도 hello에 대한 도시 사전 결과를 반환하기 전에 "olleh"를 실제로 게시하도록하는 유일한 옵션이 있습니까?

+0

당신은 [스레드] (http://docs.python.org/2/library/thread.html)의 필요! –

+1

'threading'. 또한 자바 배경에서오고 있습니까? 모든 것을하기 위해 클래스를 필요로하지는 않습니다. – roippi

+0

스레드가 필요하지 않습니다. Twisted, grequests 또는 심지어 하위 프로세스를 사용할 수 있습니다. 파이썬 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 
관련 문제