在python3中使用importlib进行动态导入时出错 [英] Errors while dynamic imports using importlib in python3

查看:190
本文介绍了在python3中使用importlib进行动态导入时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试将 importlib 与python3(3.6)结合使用.

I have been trying to use importlib with python3 (3.6).

目录结构

main.py

#Note: I will only modify line 4 that uses importlib
import importlib
if __name__ == '__main__':
    print("In main.py")
    hello = importlib.import_module('hello', package='./')
    print("Loaded hello.py")
    hello.hello()

hello.py

def hello():
    print('Hello world')

文件夹/hello.py

def hello():
    print('Hello world in folder')

观察

如果我这样做

hello = importlib.import_module('hello',package ='./')

hello = importlib.import_module('hello')

它从根文件夹中导入 hello.py 并打印 hello world .

It imports hello.py from the root folder and prints hello world.

如果我这样做

hello = importlib.import_module('folder.hello')

它从根文件夹导入 folder/hello.py 并在文件夹中输出 hello world .

It imports folder/hello.py from the root folder and prints hello world in folder.

但是,如果我这样做

hello = importlib.import_module('hello',package ='folder')

hello = importlib.import_module('hello',package ='./folder')

出现错误

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    hello = importlib.import_module('hello', package='./folder')
  File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'hello'

问题

我不确定这是怎么回事.我很确定我对python模块和软件包的理解有问题.有人可以解释为什么这是预期的行为吗?

I am not sure what is going on here. I am pretty sure there is something wrong with my understanding of python modules and packages. Can someone explain why this is the expected behavior?

推荐答案

如果要导入的模块的第一个参数是绝对模块引用(没有前导.),则第二个参数为完全被忽略.

If the first argument, the module to be imported is an absolute module reference ( has no leading .), the seond argument is completely ignored.

要相对于另一个模块 b 导入模块 a ,您必须使用

To import a module a relative to another module b, you have to use

a = importlib.import_module('.a', package='b')

在您的情况下,这应该可行

In your case, this should work

hello = importlib.import_module('.hello', package='folder')

根据经验,如果要使用 package 作为第二个参数,则 import package 应该可以工作.

As a rule of thumb, import package should work if you want to use package as second argument.

from package import module

然后变成

importlib.import_module(module, package)

这篇关于在python3中使用importlib进行动态导入时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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