Backgroundworker in python

情到浓时终转凉″ 提交于 2019-12-21 20:44:43

问题


I'm an inexperienced python programmer.

Is there a way to use the backgroundworker so that it starts at program startup and closes when program close?

I want it to watch a button, the button returns 1 when pressed. So while the program in running whenever button = 1 button has to do "this".

Can anyone help me with this?


回答1:


Would make sense to start a separate thread within your main program and do anything in the background. As an example check the fairly simple code below:

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)



回答2:


As of Python 3.3, the Thread constructor has a daemon argument. Konstantin's answer works, but I like the brevity of needing only one line to start a thread:

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

As the documentation mentions, daemon threads exit as soon as the main thread exit, so you still need to keep your main thread busy while the background worker does its thing. In my case, I start a web server after starting the thread.



来源:https://stackoverflow.com/questions/22832834/backgroundworker-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!