1. 程式人生 > >importError: No module named site

importError: No module named site

Python 環境變數

下面幾個重要的環境變數,它應用於Python:

變數名 描述
PYTHONPATH PYTHONPATH是Python搜尋路徑,預設我們import的模組都會從PYTHONPATH裡面尋找。
PYTHONSTARTUP Python啟動後,先尋找PYTHONSTARTUP環境變數,然後執行此變數指定的檔案中的程式碼。
PYTHONCASEOK 加入PYTHONCASEOK的環境變數, 就會使python匯入模組的時候不區分大小寫.
PYTHONHOME 另一種模組搜尋路徑。它通常內嵌於的PYTHONSTARTUP或PYTHONPATH目錄中,使得兩個模組庫更容易切換。

通常我們會在命令列上設定PYTHONPATH。在執行指令碼之前先執行設定PYTHONPATH的命令。

例如windows上,設定PYTHONPATH的命令為:

  1. SET ROOT_DIR=%~dp0  
  2. SET PYTHONPATH=%PYTHONPATH%;%ROOT_DIR%src\main\python;%ROOT_DIR%src\test\python;%ROOT_DIR%generated\pyxb;%ROOT_DIR%  
這樣就將我們在當前目錄下的src\main\python,src\test\python,generated\pyxb三個資料夾放到pythonpath裡面了,我們就可以直接匯入這三個資料夾裡面的模組了。

You know what has worked for me really well on windows.

My Computer > Properties > Advanced System Settings > Environment Variables >

Then under system variables I create a new Variable called PythonPath. In this variable I have C:\Python27\Lib;C:\Python27\DLLs;C:\Python27\Lib\lib-tk;C:\other-folders-on-the-path

enter image description here

This is the best way that has worked for me which I hadn't found in any of the docs offered.

EDIT: For those who are not able to get it, Please add

C:\Python27;

along with it. Else it will never work.


今天在除錯Evernote SDK時, 遇到PythonPath的問題。 查了很多資料,有說用系統環境變數新增PythonPath, 有說在登錄檔中的PythonPath新增新Default欄位, 但是對於我來說都沒有效果, 很奇怪。 
最後還是在程式碼裡顯式新增sys.path才好用:

import sys
import hashlib
import binascii
import time

if "..\\lib" not in sys.path:
     sys.path.append(r"..\\lib")

Windows 7 Professional I Modified @mongoose_za's answer to make it easier to change the python version:

  1. [Right Click]Computer > Properties >Advanced System Settings > Environment Variables
  2. Click [New] under "System Variable"
  3. Variable Name: PY_HOME, Variable Value:C:\path\to\python\version enter image description here
  4. Click [OK]
  5. Locate the "Path" System variable and click [Edit]
  6. Add the following to the existing variable:

    %PY_HOME%;%PY_HOME%\Lib;%PY_HOME%\DLLs;%PY_HOME%\Lib\lib-tk; enter image description here

  7. Click [OK] to close all of the windows.

As a final sanity check open a command prompt and enter python. You should see

>python [whatever version you are using]

If you need to switch between versions, you only need to modify the PY_HOME variable to point to the proper directory. This is bit easier to manage if you need multiple python versions installed.