Running a Python script for a user-specified amount of time

I recommend spawning another thread, making it a daemon thread, then sleeping until you want the task to die. For example:

from time import sleep
from threading import Thread

def some_task():
    while True:
        pass

t = Thread(target=some_task)  # run the some_task function in another
                              # thread
t.daemon = True               # Python will exit when the main thread
                              # exits, even if this thread is still
                              # running
t.start()

snooziness = int(raw_input('Enter the amount of seconds you want to run this: '))
sleep(snooziness)

# Since this is the end of the script, Python will now exit.  If we
# still had any other non-daemon threads running, we wouldn't exit.
# However, since our task is a daemon thread, Python will exit even if
# it's still going.

The Python interpreter will shut down when all non-daemon threads have exited. So when your main thread exits, if the only other thread running is your task that you are running in a separate daemon thread, then Python will just exit. This is a convenient way of running something in the background if you want to be able to just quit without worrying about manually causing it to quit and waiting for it to stop.

So in other words, the advantage which this approach has over using sleep in a for loop is in that case you have to code your task in such a way that it’s broken up into discrete chunks and then check every so often whether your time is up. Which might be fine for your purposes, but it can have problems, such as if each chunk takes a significant amount of time, thus causing your program to run for significantly longer than what the user entered, etc. Whether this is a problem for you depends on the task you are writing, but I figured I would mention this approach in case it would be better for you.

Leave a Comment