这真的取决于你想要达到的目标。例如,对于自动加载丢失的包,您可以执行类似于 page
的操作
import os.path
try:
import some_module
except ImportError:
import pip
pip.main(['install', '--user', 'some_module'])
os.execv(__file__,sys.argv)
如果您想动态加载某些内容,您可以使用__init__.py 文件和以下代码(我在一些旧脚本中使用它来加载演说家迁移模式文件)。不过你需要import * from <whatever_folder_has_this_init_file>:
import importlib
import inspect
import glob
from os.path import dirname, basename, isfile, join
def __get_defined_modules():
modules_path = join(dirname(__file__), "migrations", "*.py")
modules = glob.glob(modules_path)
for f in modules:
if isfile(f) and f.find('migration'):
yield basename(f)[:-3]
def run_migrations(db):
m = __get_defined_modules()
for x in m:
if x.find('migration') > -1:
module_path='{}.migrations.{}'.format(basename(dirname(__file__)), x)
for _, cls in inspect.getmembers(importlib.import_module(module_path), inspect.isclass):
if cls.__module__ == module_path:
print("Loading and executing {}: {}".format(x, cls))
migration = cls()
migration.set_connection(db)
migration.up()
__all__ = list(__get_defined_modules()) + ['run_migrations']
另一种方式(我并不真正推荐)是使用这种方式(我没有测试过):
import inspect, importlib def try_xx()
try:
some_xx()
except NameError as e:
func_name = e.split("'")[1]
parts = func_name.split("_")
for _, f in inspect.getmembers(importlib.import_module("/module/path/{}.py".format(parts[1])), inspect.isfunction):
if f.__name__ == func_name:
f()
但是要回答您的问题...不,python 没有内置的自动加载机制,因为大多数时候您都不需要它。您可以在此处阅读有关原因的详细说明:Python modules autoloader?(关于 php,它也具有自动加载功能,但您会明白的)