在新线程中运行Python程序
我有两个程序。
program1.py 就像一个命令行界面,可以接收用户的命令。
program2.py 则是根据命令运行相应程序的地方。
程序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()
现在 program2 有
def say_hi():
#do something..
现在可能有两种情况...
要么 say_hi() 完成了,这样就没问题...
但我想要的是,如果用户输入一个命令(比如:end),那么这个 say_hi() 就会在中间被终止。
但是我现在的实现方式是非常顺序的...我的意思是,在执行完成之前,我无法在终端上输入任何东西。
有种感觉告诉我,say_hi() 应该在另一个线程上运行?
我现在想不清楚这个问题。
有什么建议吗?
谢谢!
1 个回答
15
你需要的就是线程模块。
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
顺便提一下,你必须确保在线程中使用线程安全的函数。在打招呼的例子中,你应该使用日志模块,而不是直接用print()。
import logging
logging.info('I am saying hi in a thread-safe manner')
你可以在Python文档中阅读更多内容。