2017-12-12 14 views
0

Ich bin nicht in der Lage, ein Modul dynamisch zu importieren, das ich problemlos in Code importieren kann, und ich habe keine Ahnung warum.Python3: anderes Verhalten zwischen import und importlib.import_module?

Ich habe folgendes:

> ls lib 
__init__.py  main.py 

Die init-Datei leer ist. Die folgenden Werke:

> python3 
Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
[GCC 4.8.4] on linux 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import lib.main 
>>> lib.main.sayyay() 
yay 

Die folgende nicht funktioniert:

> python3 
Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
[GCC 4.8.4] on linux 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import importlib 
>>> importlib.import_module("lib.main") 
<module 'lib.main' from '/some/path/lib/main.py'> 
>>> lib.main.sayyay() 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
NameError: name 'lib' is not defined 

ich die importlib Dokumentation sowie ein paar Antworten hier auf SO gelesen haben, zum Beispiel How to import a module in Python with importlib.import_module und Dynamically import a method in a file, from a string

Aber was vermisse ich?

Antwort

1

import_module gibt das importierte Modul zurück. Daher müssen Sie das importierte Modul einen Namen geben und diese wie nur lib.main verwenden

>>> lib_main = importlib.import_module("lib.main") 
>>> lib_main.sayyay() 
+0

Oh, das war unerwartet. Aber ich sehe, wie das nützlich sein kann. Vielen Dank. – BaCh

Verwandte Themen