如何在Python中导入第三方模块?
我找到一个第三方模块,想要使用它。请问我该怎么技术性地导入这个模块呢?
具体来说,我想用一个叫做 context_manager 的模块。显然,我不能直接用 import garlicsim.general_misc.context_manager
,因为它找不到 garlicsim
。那我应该怎么写才能导入这个东西呢?
编辑:我同时在使用 Python 3.x 和 Python 2.x,希望能得到适用于这两个版本的答案。
3 个回答
0
安装
GarlicSim已经不再更新了,但你仍然可以在这里找到它,并且可以下载:
C:\Python27\Scripts>pip search garlicsim
garlicsim_lib - Collection of GarlicSim simulation packages
garlicsim_lib_py3 - Collection of GarlicSim simulation packages
garlicsim_wx - GUI for garlicsim, a Pythonic framework for
computer simulations
garlicsim - Pythonic framework for working with simulations
garlicsim_py3 - Pythonic framework for working with simulations
使用 pip install garlicsim
来安装它。
使用方法
根据Python的风格指南:
导入的内容应该放在文件的最上面,紧接着模块的注释和文档字符串,然后是模块的全局变量和常量。
导入的内容应该按以下顺序分组:
- 标准库的导入
- 相关的第三方库导入
- 本地应用或库特定的导入
每组导入之间应该留一行空行。
>>> import garlicsim.general_misc.context_manager as CM
>>> help(CM)
Help on module garlicsim.general_misc.context_manager in garlicsim.general_misc:
NAME
garlicsim.general_misc.context_manager - Defines the `ContextManager` and `ContextManagerType` classes.
FILE
c:\python27\lib\site-packages\garlicsim\general_misc\context_manager.py
DESCRIPTION
Using these classes to define context managers allows using such context
managers as decorators (in addition to their normal use) and supports writing
context managers in a new form called `manage_context`. (As well as the
original forms).
[...]
>>> from garlicsim.general_misc.context_manager import ContextManager
>>> help(ContextManager)
Help on class ContextManager in module garlicsim.general_misc.context_manager:
class ContextManager(__builtin__.object)
| Allows running preparation code before a given suite and cleanup after.
替代方案
看起来在Python 3.2中已经有了这个功能:
class contextlib.ContextDecorator - 这是一个基类,可以让上下文管理器也能作为装饰器使用。
而contextmanager早在Python 2.5就已经存在了:
from contextlib import contextmanager
@contextmanager
def tag(name):
print "<%s>" % name
yield
print "</%s>" % name
>>> with tag("h1"):
... print "foo"
...
<h1>
foo
</h1>
1
你需要把这个模块安装到你的PYTHONPATH里面。对于几乎所有的Python模块,你可以使用 easy_install
或者这个模块自带的 setup.py
脚本来帮你完成安装。