2024-04-20 02:57:26 发布
网友
要导入模块,需要临时或永久地将其目录添加到环境变量中。
import sys sys.path.append("/path/to/my/modules/") import my_module
将以下行添加到.bashrc文件(在linux中)并在终端中执行source ~/.bashrc:
.bashrc
source ~/.bashrc
export PYTHONPATH="${PYTHONPATH}:/path/to/my/modules/"
信用/来源:saarrrr,another 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。
要导入模块,需要临时或永久地将其目录添加到环境变量中。
暂时
永久
将以下行添加到
.bashrc
文件(在linux中)并在终端中执行source ~/.bashrc
:信用/来源:saarrrr,another stackexchange question
将路径添加到sys.path(而不是使用imp)的好处是,它简化了从单个包导入多个模块的过程。例如:
对于Python3.5+使用:
对于Python3.3和3.4,请使用:
(尽管这在Python3.4中已被弃用。)
对于Python2使用:
对于已编译的Python文件和dll,有等效的便利函数。
另请参见http://bugs.python.org/issue21436。
相关问题 更多 >
编程相关推荐