我有一个名为命令的模块文件夹。
这些模块中都有一个唯一的命名函数。
从主目录,带有命令文件夹的那个,我有一个main.py
我可以使用from commands import *
有没有办法导入所有模块中的所有功能而无需单独导入它们。即使使用for循环也没关系。
答案 0 :(得分:1)
假设您有一个目录,其中包含一些python文件(.py)和一个main.py
(在同一目录中),您希望其他文件的所有功能都可用。这是一个天真的方法(一个坏主意,真的),当然,要注意名称冲突:
内部main.py
:
from os import listdir
from importlib import import_module
for file in listdir('.'):
if file.endswith('.py') and file not in __file__:
module_name = file[:file.index('.py')]
# if you want all functions to just this file (main.py) use locals(); if you want the caller of main.py to have access, use globals()
globals().update(import_module(module_name).__dict__)
# Functions defined in all other .py files are available here