Skip to content
Advertisement

background function in Python

I’ve got a Python script that sometimes displays images to the user. The images can, at times, be quite large, and they are reused often. Displaying them is not critical, but displaying the message associated with them is. I’ve got a function that downloads the image needed and saves it locally. Right now it’s run inline with the code that displays a message to the user, but that can sometimes take over 10 seconds for non-local images. Is there a way I could call this function when it’s needed, but run it in the background while the code continues to execute? I would just use a default image until the correct one becomes available.

Advertisement

Answer

Do something like this:

def function_that_downloads(my_args):
    # do some long download here

then inline, do something like this:

import threading
def my_inline_function(some_args):
    # do some stuff
    download_thread = threading.Thread(target=function_that_downloads, name="Downloader", args=some_args)
    download_thread.start()
    # continue doing stuff

You may want to check if the thread has finished before going on to other things by calling download_thread.isAlive()

Advertisement