2012-05-10 52 views
9

我知道我可以添加一個導入路徑到Python這樣的:如何永久添加Python導入路徑?

import sys 

sys.path.append("/path/to/directory/") 

但是,當我重新啓動的Python,這已經一去不復返了。如果我不得不一直這樣做,我會覺得很煩人,我希望一勞永逸地做到這一點,並做到這一點。

那麼,怎麼樣?我在哪裏可以找到該文件?還是我需要編輯別的東西?我正在使用最新版本的Ubuntu。

+0

http://docs.python.org/install/index.html#modifying-python-s-search-path – georg

回答

8

人蟒

~/.pythonrc.py 
      User-specific initialization file loaded by the user module; not used by default or by most applications. 

ENVIRONMENT VARIABLES 

    PYTHONPATH 
      Augments the default search path for module files. The format is the same as the shell's $PATH: one or more directory pathnames 
      separated by colons. Non-existent directories are silently ignored. The default search path is installation dependent, but gen- 
      erally begins with ${prefix}/lib/python<version> (see PYTHONHOME above). The default search path is always appended to $PYTHON- 
      PATH. If a script argument is given, the directory containing the script is inserted in the path in front of $PYTHONPATH. The 
      search path can be manipulated from within a Python program as the variable sys.path . 
2

執行從殼以下:

echo -e "\nexport PYTHONPATH=\$PYTHONPATH:/path/to/directory" >> ~/.bashrc 

,並重新啓動它

+0

我這樣做了,但沒有任何改變。我是否需要重新啓動,也許? – corazza

+0

@Bane, 1)我編輯了這行,出現了一個錯誤。 2)通常你必須重新登錄你的shell(只需關閉並再次打開) 3)你可能還想編輯〜/ .bashrc並刪除你輸入的錯誤命令添加的行 4)最後,別忘了用實際路徑替換'path/to/directory'。 – dmytro

3

您可以設置一個名爲PYTHONPATH你include目錄的環境變量。

瞭解更多關於它的docs

4

您還可以使用路徑文件。

如果要將名爲mymodule的模塊添加到導入路徑中,請將文件mymodule.pth添加到第三方模塊(通常稱爲dist-packages或site-packages)的標準目錄中。在Ubuntu上你可能會發現它的地方,喜歡

/usr/local/lib/python2.7/dist-packages 

文件mymodule.pth應該包含單行線,要添加到Python的導入路徑

<mymodule.pth> 
/path/to/directory/containing/mymodule 

任何Python模塊或軟件包的目錄在目錄中現在可以從解釋器導入。