Python中的后台工作线程
我还是个新手,刚开始学Python编程。
有没有办法让后台工作者在程序启动时就开始运行,并在程序关闭时自动结束呢?
我想让它监控一个按钮,当按钮被按下时返回1。所以在程序运行期间,只要按钮等于1,就要执行“这个操作”。
有没有人能帮我解决这个问题?
2 个回答
4
从Python 3.3开始,线程的构造函数里有一个叫daemon
的参数。Konstantin的回答是有效的,但我更喜欢只用一行代码就能启动一个线程的简洁方式:
import threading, time
MAINTENANCE_INTERVAL = 60
def maintenance():
""" Background thread doing various maintenance tasks """
while True:
# do things...
time.sleep(MAINTENANCE_INTERVAL)
threading.Thread(target=maintenance, daemon=True).start()
正如文档中提到的,守护线程会在主线程结束时立刻退出,所以你仍然需要让主线程保持忙碌,这样后台工作线程才能正常运行。在我的例子中,我是在启动线程后再启动一个网络服务器。
15
在你的主程序中启动一个单独的线程来处理一些后台任务是个不错的主意。下面的代码就是一个比较简单的例子:
import threading
import time
#Routine that processes whatever you want as background
def YourLedRoutine():
while 1:
print 'tick'
time.sleep(1)
t1 = threading.Thread(target=YourLedRoutine)
#Background thread will finish with the main program
t1.setDaemon(True)
#Start YourLedRoutine() in a separate thread
t1.start()
#You main program imitated by sleep
time.sleep(5)