在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