如何在分离的线程Python中运行类?

时间:2018-02-18 15:41:00

标签: python python-3.x

我在Python脚本中有两个类。其中一个是Main(),第二个是Loading()

class Main:
   pass

class Loading:
   pass

首先,返回的作品Main()填充字典

然后创建Loading()的实例,迭代所有图像并下载它们:

## LOAD IMAGES ##
imageLoader = Loading()
imageLoader.save()

所以,问题是当我调用这个脚本时,它会创建一个等待imageLoader = Loading()结束的主线程。

因此,主线程工作时间过长,会调用502 Server错误。

如何在一个单独的后台线程中运行imageLoader = Loading()以释放主线程?

此代码中首先推出的内容:

LOADED_IMAGES = {}
IMAGES_ERRORS = []
IMAGES = {"A": "https://images.aif.ru/009/299/3378e1a1ab2d1c6e6be6d38253dd3632.jpg", "B": "http://static1.repo.aif.ru/1/77/623957/b99ee5f894f38261e4d3778350ffbaae.jpg"}

    excel = Excel()
    excel.readExcel(file_path, 'Main')

    imageLoader = ImageLoader()
    Thread(target=imageLoader.run().save()).start()

Does it work line by line or Thread will be created immediately?


**This is full code:**

    class ImageLoader:
        def run(self):
            for article, image in IMAGES.items():
                if image is None or image == '':
                    continue
                LOADED_IMAGES[article] = self.loadImage(self.replaceHttpsProtocol(image), '/home/o/oliwin4/jara/public_html/image/catalog/s/')

        def replaceHttpsProtocol(self, url):
            return url.replace("https:", "http:")

        def nameNameGenerate(self):
            return int(round(time.time() * 1000))

        def extention(self, path):
            ext = path.split(".")[-1]
            return '.' + ext if ext else "jpg"

        def save(self):
            for article, image in LOADED_IMAGES.items():
                self.add(article, image)

        def add(self, article, image):
            Products.update(image=image).where(Products.sku == article).execute()

        def loadImage(self, path, path_folder):
            try:

                filename = str(self.nameNameGenerate()) + str(self.extention(path))
                wget.download(url=path, out=path_folder + filename)
                return 'catalog/s/' + filename

            except BaseException as e:
                IMAGES_ERRORS.append(str(e))

是:

def runOnThread():
    imageLoader = ImageLoader()
    imageLoader.run()
    imageLoader.save()

if __name__ == "__main__":
     Thread(target=runOnThread, daemon=True).start()

2 个答案:

答案 0 :(得分:0)

你需要查找哪一行阻止你的代码在一个独立的线程中运行它,通常阻塞行是某种I / O或昂贵的计算。

为此,您可以使用线程模块。

所以,假设您的阻止线是

imageLoader.save()

尝试使用此代码在单独的线程中运行它。

from threading import Thread

Thread(target=imageLoader.save()).start()

答案 1 :(得分:0)

如前所述,您可以使用Python的threading模块。虽然,一个线程接受一个函数的引用(传递target函数调用是无用的/错误的。)

在你的情况下,如果你想要实例化然后在一个单独的线程中对一个对象运行一个函数,你应该将这两个放在一个函数中:

def runOnThread():
    imageLoader = Loading()
    imageLoader.save()

然后将此函数的引用传递给新线程,如此(注意没有()):

from threading import Thread
Thread(target=runOnThread).start()

如果您不希望主线程等待新线程完成,您可以将其设为Daemon线程,如下所示:

Thread(target=runOnThread, daemon=True).start()

上述所有内容的缩短版本:

from threading import Thread
Thread(target=lambda: Loading().save(), daemon=True).start()