給定完整路徑,如何加載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的解決方案在命令行上有效,但不是在程序內部。 文檔