给定完整路径,如何加载Python模块? 请注意,该文件能够在文件系统中的任何位置,由于它是配置选项。 html
(经过使用imp)向sys.path添加路径的优势是,当从单个包中导入多个模块时,它能够简化操做。 例如: python
import sys # the mock-0.3.1 dir contains testcase.py, testutils.py & mock.py sys.path.append('/foo/bar/mock-0.3.1') from testcase import TestCase from testutils import RunTests from mock import Mock, sentinel, patch
您能够使用pkgutil
模块(特别是walk_packages
方法)来获取当前目录中的软件包列表。 从那里开始,使用importlib
机械导入所需的模块很简单: app
import pkgutil import importlib packages = pkgutil.walk_packages(path='.') for importer, name, is_package in packages: mod = importlib.import_module(name) # do whatever you want with module now, it's been imported!
在Linux中,能够在python脚本所在的目录中添加符号连接。 spa
即: 命令行
ln -s /absolute/path/to/module/module.py /absolute/path/to/script/module.py
若是您更改/absolute/path/to/module/module.py
的内容,python将建立/absolute/path/to/script/module.pyc
并进行更新。 code
而后在mypythonscript.py中包含如下内容 htm
from module import *
我认为,最好的方法是从官方文档中获取( 29.1。imp —访问import internals ): ip
import imp import sys def __import__(name, globals=None, locals=None, fromlist=None): # Fast path: see if the module has already been imported. try: return sys.modules[name] except KeyError: pass # If any of the following calls raises an exception, # there's a problem we can't handle -- let the caller handle it. fp, pathname, description = imp.find_module(name) try: return imp.load_module(name, fp, pathname, description) finally: # Since we may exit via an exception, close fp explicitly. if fp: fp.close()
Python 3.4的这一领域彷佛很难理解! 可是,使用Chris Calloway的代码进行了一些黑客操做,我设法使某些工做正常进行。 这是基本功能。 ci
def import_module_from_file(full_path_to_module): """ Import a module given the full path/filename of the .py file Python 3.4 """ module = None try: # Get module name and path from full path module_dir, module_file = os.path.split(full_path_to_module) module_name, module_ext = os.path.splitext(module_file) # Get module "spec" from filename spec = importlib.util.spec_from_file_location(module_name,full_path_to_module) module = spec.loader.load_module() except Exception as ec: # Simple error printing # Insert "sophisticated" stuff here print(ec) finally: return module
这彷佛使用了Python 3.4中不推荐使用的模块。 我不伪装理解为何,可是它彷佛能够在程序中运行。 我发现Chris的解决方案在命令行上有效,但不是在程序内部。 文档