python动态加载模块有什么用_在python3中动态加载模块

在Python3中,建议使用哪种方法延迟加载文件?在

我通过从python2代码复制过去构建了这个函数def get_command(self, ctx, cmd_name):

ns = {}

fn = os.path.join(cmd_folder, 'cmd_{}.py'.format(cmd_name))

with open(fn) as f:

code = compile(f.read(), str(fn), 'exec')

eval(code, ns, ns)

return ns['cli']

但我不确定这是不是正确的方法。它使用compile和{}

编辑

像这样使用import之后:

^{pr2}$

结果是:File "aws_iam_cli/cli.py", line 23, in get_command

cmd_mod = import_module('{}.cmd_{}'.format(cmd_folder, cmd_name))

File "/Users/salvatoremazzarino/awsiam/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module

return _bootstrap._gcd_import(name[level:], package, level)

File "", line 994, in _gcd_import

File "", line 971, in _find_and_load

File "", line 941, in _find_and_load_unlocked

File "", line 219, in _call_with_frames_removed

File "", line 994, in _gcd_import

File "", line 971, in _find_and_load

File "", line 953, in _find_and_load_unlocked

ModuleNotFoundError: No module named '/Users/salvatoremazzarino/awsiam/aws_iam_cli/commands'

编辑2:def get_command(self, ctx, cmd_name):

mod = import_module('aws_iam_cli.commands.cmd_{}'

.format(cmd_name))

return mod.cli

错误是:File "/Users/salvatoremazzarino/awsiam/venv/lib/python3.6/importlib/__init__.py", line 126, in import_module

return _bootstrap._gcd_import(name[level:], package, level)

File "", line 994, in _gcd_import

File "", line 971, in _find_and_load

File "", line 941, in _find_and_load_unlocked

File "", line 219, in _call_with_frames_removed

File "", line 994, in _gcd_import

File "", line 971, in _find_and_load

File "", line 941, in _find_and_load_unlocked

File "", line 219, in _call_with_frames_removed

File "", line 994, in _gcd_import

File "", line 971, in _find_and_load

File "", line 953, in _find_and_load_unlocked

ModuleNotFoundError: No module named 'aws_iam_cli'

这是目录树:├── aws_iam_cli

│   ├── __init__.py

│   ├── cli.py

│   ├── commands

│   │   ├── __init__.py

│   │   ├── __pycache__

│   │   └── cmd_dump.py

│   └── provider

│   ├── __init__.py

│   ├── policy.py

│   └── role.py

在命令内部我有一个模块,我在该模块中调用:from aws_iam_cli.provider.role import fetch_roles

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值