/ / Import asynchrone en Python - multithreading, python-3.x, asynchrone, python-import, python-multithreading

Importation asynchrone en Python - multithreading, python-3.x, asynchrone, python-import, python-multithreading

J'ai besoin d'importer quelque chose de grand etCela coûte cher, mais je n’en ai pas besoin tout de suite dans mon application. Existe-t-il un moyen d’importer quelque chose de manière asynchrone en python, c’est-à-dire que tout ce que l’importation doit faire se fait en arrière-plan lorsque mon script est en cours d’exécution? loin.

Réponses:

1 pour la réponse № 1

Vous pouvez appeler l'importateur python en tant que fonction dans un autre thread au lieu d'utiliser import foo. Étant donné que cette importation est coûteuse en ressources informatiques et que python ne permet qu’un seul thread à la fois (sauf si pandas qui libère le GIL), vous ne trouverez que peu d’avantages. Encore,

import threading
import time

def begin_load_foo():
global foo_thread
foo_thread = threading.Thread(target=load_foo_thread)
foo_thread.start()

def load_foo_thread():
global foo
print("start importing")
foo = __import__("foo")
print("done importing")

def wait_foo():
print("wait")
foo_thread.join()
print("done")

def do_other_things():
time.sleep(1)

begin_load_foo()
do_other_things()
wait_foo()
foo.bar()