2011-02-01 69 views
6

我找到了我想要使用的第三方模塊。我如何從技術上導入該模塊?如何導入Python中的第三方模塊?

特別是,我想使用一個名爲context_manager的模塊。顯然,我不能只是import garlicsim.general_misc.context_manager,因爲它不會找到garlicsim。那麼我應該寫什麼來導入這個東西呢?

編輯:我正在使用Python 3.x和Python 2.x,我想得到兩個版本的相關答案。

+0

你使用python 2或Python 3?該鏈接適用於python 3軟件包。 – chmullig 2011-02-01 23:07:59

回答

6

在garlicsim的情況下,你想安裝它下面的蒜大蒜的installation instructions。您也可以下載代碼並在正確的目錄中運行python setup.py install以獲取此庫和幾乎任何其他庫。

一個注意,因爲你可能是python的新手,那是python 3庫。如果你使用的是Python 2(更可能如果你不知道),它將無法正常工作。你會想安裝python 2 version

1

您需要在您的PYTHONPATH中的某處安裝模塊。對於幾乎所有的python模塊,您可以使用easy_install或包的自己的setup.py腳本爲您執行此操作。

0

安裝

GarlicSim is deadstillavailable

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安裝它。

使用

根據the Python style guide

進口量始終把在文件的頂部,只是任何模塊 意見和文檔字符串,和之前模塊全局變量和常量之後。

  1. 標準庫進口
  2. 相關第三方進口
  3. 本地應用程序/庫特定進口

你應該把一個空行:

進口量應按照下列順序進行分組每組進口之間。

>>> 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>