python dynamic import modules, functions, classes, objects

Look kennethreitz write pip-POP , runtime found my pip version 19.1 is too high, we need to change about his code. This process must consider the dynamic import.

The following is the modified bin / pip-grep beginning of the file

import os
from docopt import docopt
import importlib
# from pip.req import parse_requirements
# from pip.index import PackageFinder
# from pip._vendor.requests import session


def pip_import(module, func):
    try:  # for pip >= 10
        mod = importlib.import_module("._internal." + module, 'pip')
    except ImportError:  # for pip <= 9.0.3
        mod = importlib.import_module('.' + module, 'pip') # 动态导入模块
    return getattr(mod, func)

parse_requirements = pip_import('req', 'parse_requirements')
PackageFinder = pip_import('index', 'PackageFinder')
session = pip_import('_vendor.requests', 'session') # 动态导入函数

requests = session() # 使用导入的函数

Tested available.

Where the acquisition module name, and module methods of any objects in the file:

import sys
mod = sys.modules[__name__] # 获取所在模块
file = getattr(mod, '__file__', None) # 获取模块的文件路径
#mod = sys.modules['__main__'] # 也可以获取所在模块
print("mod:", mod) # <module '__main__' from './bin/pip-grep'>
print("file:", file) # ./bin/pip-grep
print("dir:", dir(mod)) # 获取模块中的所有对象名,包含导入的模块,类,函数,变量等
Published 135 original articles · won praise 7 · views 30000 +

Guess you like

Origin blog.csdn.net/math_computer/article/details/104055646