Daniel Harrin Daniel Harrin - 1 month ago 7
Python Question

Python functions run as background processes

I know there are ways of making a program wait for a function to finish, but is there a way to make the function, once called, to carry on in the background of a program.

This might be especially useful if you were making a program timer, like the one below.

import time
count = 0
def timer():
while True():
time.sleep(60)
count += 1
print("This program has now been running for " + str(count) + " minutes"
timer() # Carry this function out in the background
print("Hello! Welcome to the program timer!")
name = raw_input("What is your name?")
print("Nice to meet you, " + name + "!")
# More stuff here...


I hope there is a way to do background processes in python.

Answer

This sounds like threading.

The threading module is relatively simple, but beware doing any CPU bound activities that way. With lots of timers and sleeps, or IO bound then this is fine.

Threading module example:

import time
from threading import Thread

def timer(name):
    count = 0
    while True:
        time.sleep(60)
        count += 1            
        print("Hi " + name + "This program has now been running for " + str(count) + " minutes.")

print("Hello! Welcome to the program timer!")
name = raw_input("What is your name?")
print("Nice to meet you, " + name + "!")
background_thread = Thread(target=timer, args=(name,))
background_thread.start()

To Clarify - relatively simple compared with the multiprocessing module - which you may want to look at if your background activity is CPU heavy.

The python docs have a good tutorial on this at: https://docs.python.org/2/library/threading.html#thread-objects

Comments