如何导入给定完整路径的模块?

2024-04-20 02:57:26 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

要导入模块,需要临时或永久地将其目录添加到环境变量中。

暂时

import sys
sys.path.append("/path/to/my/modules/")
import my_module

永久

将以下行添加到.bashrc文件(在linux中)并在终端中执行source ~/.bashrc

export PYTHONPATH="${PYTHONPATH}:/path/to/my/modules/"

信用/来源:saarrrranother stackexchange question

将路径添加到sys.path(而不是使用imp)的好处是,它简化了从单个包导入多个模块的过程。例如:

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

对于Python3.5+使用:

import importlib.util
spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py")
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.MyClass()

对于Python3.3和3.4,请使用:

from importlib.machinery import SourceFileLoader

foo = SourceFileLoader("module.name", "/path/to/file.py").load_module()
foo.MyClass()

(尽管这在Python3.4中已被弃用。)

对于Python2使用:

import imp

foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()

对于已编译的Python文件和dll,有等效的便利函数。

另请参见http://bugs.python.org/issue21436

相关问题 更多 >