我找到了我想要使用的第三方模块。我如何从技术上导入该模块?如何导入Python中的第三方模块?
特别是,我想使用一个名为context_manager的模块。显然,我不能只是import garlicsim.general_misc.context_manager
,因为它不会找到garlicsim
。那么我应该写什么来导入这个东西呢?
编辑:我正在使用Python 3.x和Python 2.x,我想得到两个版本的相关答案。
我找到了我想要使用的第三方模块。我如何从技术上导入该模块?如何导入Python中的第三方模块?
特别是,我想使用一个名为context_manager的模块。显然,我不能只是import garlicsim.general_misc.context_manager
,因为它不会找到garlicsim
。那么我应该写什么来导入这个东西呢?
编辑:我正在使用Python 3.x和Python 2.x,我想得到两个版本的相关答案。
在garlicsim的情况下,你想安装它下面的蒜大蒜的installation instructions。您也可以下载代码并在正确的目录中运行python setup.py install
以获取此库和几乎任何其他库。
一个注意,因为你可能是python的新手,那是python 3库。如果你使用的是Python 2(更可能如果你不知道),它将无法正常工作。你会想安装python 2 version。
您需要在您的PYTHONPATH中的某处安装模块。对于几乎所有的python模块,您可以使用easy_install
或包的自己的setup.py
脚本为您执行此操作。
GarlicSim is dead但stillavailable:
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
安装它。
进口量始终把在文件的顶部,只是任何模块 意见和文档字符串,和之前模块全局变量和常量之后。
- 标准库进口
- 相关第三方进口
- 本地应用程序/库特定进口
你应该把一个空行:
进口量应按照下列顺序进行分组每组进口之间。
>>> 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.
看起来这是already in Python 3.2:
类contextlib.ContextDecorator - 一个基类,使上下文 经理也可以用作装饰。
而且contextmanager is as old as 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>
你使用python 2或Python 3?该链接适用于python 3软件包。 – chmullig 2011-02-01 23:07:59