我有一个叫做命令的模块文件夹。
这些模块中每个模块都有一个唯一的命名函数。
在主目录(包含命令文件夹的目录)中,我有一个main.py
我可以用from commands import *导入所有模块
是否有一种方法可以导入所有模块中的所有功能,而无需单独导入它们。即使使用for循环也可以。
发布于 2017-09-24 02:30:22
假设您有一个目录,其中有一些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 herehttps://stackoverflow.com/questions/46385848
复制相似问题