Question

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?

Était-ce utile?

La solution

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)

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top