假设我有20个包需要从当前目录导入,其中包含__init__.py。
from . import x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20
因此,每个单独的结构都是:
x1/__init__.py
如何从"."导入所有这些?在这种情况下,导入许多包或全部包的最蟒蛇的方式是什么?
编辑:from . import *
不适用于程序包。
我是这样创建包结构的:
d=q64611308
for i in $(seq 20); do
mkdir -p "${d}/x${i}"
echo "print('imported x${i}')" > "${d}/x${i}/__init__.py"
done
q64611308/__init__.py
文件为:
from importlib import import_module
from pprint import pprint
# from . import x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20
# Traceback (most recent call last):
# File "./__init__.py", line 1, in <module>
# from . import x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20
# ImportError: cannot import name 'x1'
modnames = [f"x{i}" for i in range(1, 21)]
for modname in modnames:
print(f"importing {modname}")
locals()[modname] = import_module(modname)
pprint(locals())
这些:
$ python3 q64611308/__init__.py
$ cd q64611308; python3 ./__init__.py
将同时打印:
importing x1
imported x1
importing x2
imported x2
[...]
importing x19
imported x19
importing x20
imported x20
{'__annotations__': {},
'__builtins__': <module 'builtins' (built-in)>,
'__cached__': None,
'__doc__': None,
'__file__': './__init__.py',
[...]
'pprint': <function pprint at 0x1080817b8>,
'x1': <module 'x1' from '[...]/stackoverflow/q64611308/x1/__init__.py'>,
'x10': <module 'x10' from '[...]/stackoverflow/q64611308/x10/__init__.py'>,
[...]
'x8': <module 'x8' from '[...]/stackoverflow/q64611308/x8/__init__.py'>,
'x9': <module 'x9' from '[...]/stackoverflow/q64611308/x9/__init__.py'>}
您可以使用*来包含所有内容。
from . import *
我认为要解决x1、x2、x3等问题,只需使用
from . import *