2013-02-08 68 views
1

我有两个程序 program1.py就像命令行界面,它接受用户的命令 program2.py具有根据命令运行相关程序的程序。在一个新线程上运行python程序

方案1还具有quit_program()模块 在我们简单的宇宙..可以说,我只有一个命令,只是一个程序 因此,可以说...

program1.py

def main(): 
    while True: 
     try: 

      command = raw_input('> ') 
      if command == "quit" : 
       return 

      if command == '': 
       continue 
     except KeyboardInterrupt: 
      exit() 

     parseCommand(command) 

然后我有:

if commmand == "hi": 
     say_hi() 

现在程序2具有

def say_hi(): 
     #do something.. 

现在有可能出现两种情况...... 要么say_hi()完成在这种情况下没有问题... 但我想要的是,如果用户输入命令(比如:结束) 那么这个say_hi( )被终止之间..

但我目前的实施是非常顺序的..我的意思是我没有得到在我的终端上键入任何东西,直到执行完成.. Somethng告诉我say_hi()应该在运行在另一个线程?

我不能直截了当地想这件事。 有什么建议吗? 谢谢

回答

6

线程模块是你在找什么。

import threading 
t = threading.Thread(target=target_function,name=name,args=(args)) 
t.daemon = True 
t.start() 

.daemon选项,可以使您不必明确杀死线程当你的应用程序退出...线程可以说是相当讨厌否则

具体到这个问题,并在评论的问题,该say_hi功能可以在另一个线程被称为例如:

import threading 
if commmand == "hi": 
    t = threading.thread(target=say_hi, name='Saying hi') #< Note that I did not actually call the function, but instead sent it as a parameter 
    t.daemon = True 
    t.start() #< This actually starts the thread execution in the background 

作为一个侧面说明,你必须确保你正在使用线程的内部线程安全的功能。在打招呼的例子,你可能需要使用记录模块,而不是打印的()

import logging 
logging.info('I am saying hi in a thread-safe manner') 

你可以阅读更多in the Python Docs

+0

嗨..但与此..我将如何能够在背景中运行“say_hi()”..?并仍然保持控制,以便我可以在终端中键入命令 – Fraz 2013-02-08 23:23:23