在后台运行类函数并检索其状态

时间:2018-05-01 20:10:36

标签: python multithreading asynchronous python-multithreading python-asyncio

import threading
from azure.storage.blob import BlockBlobService

def do_other_stuff():
    print("so much stuff to do")

class ABlob:
    def __init__(self, account_name, account_key, container_name, blob_name, file_path):
        self.account_name = account_name
        self.account_key = account_key
        self.container_name = container_name
        self.blob_name = blob_name
        self.file_path = file_path
        self.blob_service = BlockBlobService(account_name=self.account_name, account_key=self.account_key)

    def get_blob(self):
        download_thread = threading.Thread(
            target=self.blob_service.get_blob_to_path,
            args=(self.container_name, self.blob_name, self.file_path))
        download_thread.start()

    def get_blob_name(self):
        print(self.blob_name)


first_blob = ABlob(account_name='account_name',
                   account_key='key',
                   container_name='container', blob_name='something.csv',
                   file_path='path')


first_blob.get_blob()
first_blob.get_blob_name()
do_other_stuff()

我有Azure Blob需要下载和上传(未显示)。我不想等待他们完成他们的过程,因为我还有其他应该做的事情。但在某些时候,我需要确认他们是否已成功下载或上传。

使用我当前的代码,我使用了线程库。如果上载或下载过程中发生错误,则处理事务的线程将退出并显示错误。我没办法通知完成的主要线程和完成的状态。

我需要做些什么才能获得get_blob的状态?是否有另一个图书馆处理这种情况的危险性较小?我引用了以下主题,但无法弄清楚如何结合他们的不同方法。

Catch a thread's exception in the caller thread in Python

python multiprocessing pool retries

How to call a async function contained in a class

background function in Python

1 个答案:

答案 0 :(得分:1)

  

我需要做些什么才能获得get_blob的状态?

您可以将get_blob包装在一个函数中,该函数将存储有关是否成功的信息,并存储返回值(如果有)。您可以写target=self.blob_service.get_blob_to_path而不是target=self._get_blob_background。新的_get_blob_background方法可以调用self.result = self.blob_service.get_blob_to_path并使用tryexcept Exception as e来捕获所有异常,如果发生异常,则执行self.result_exception = e,以便主要线程可以将结果与异常区分开来。

更好的是,您可以使用concurrent.futures库为您完成所有这些:

pool = concurrent.futures.ThreadPoolExecutor()

def get_blob(self):
    return pool.submit(self.blob_service.get_blob_to_path,
                       self.container_name, self.blob_name, self.file_path)

现在get_blob()将在后台运行,就像在代码中一样,但在这里它会返回一个Future对象,您可以查询该对象以确定作业是否已完成,以及它是如何完成的。< / p>