Python中的后台功能 [英] background function in Python

查看:103
本文介绍了Python中的后台功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python脚本,有时会向用户显示图像.这些图像有时可能很大,并且经常重复使用.显示它们不是关键,但是显示与它们关联的消息是至关重要的.我有一个功能,可以下载所需的图像并将其保存在本地.现在,它与向用户显示消息的代码内联运行,但是对于非本地图像,有时可能会花费10秒钟以上.有没有一种方法可以在需要时调用此函数,但是可以在代码继续执行的同时在后台运行它?我只会使用默认图片,直到可以使用正确的图片为止.

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.

推荐答案

执行以下操作:

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, args=some_args)
    download_thread.start()
    # continue doing stuff

您可能想通过调用download_thread.isAlive()

这篇关于Python中的后台功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆