Python 环境变量
下面几个重要的环境变量,它应用于Python:
变量名 | 描述 |
---|---|
PYTHONPATH | PYTHONPATH是Python搜索路径,默认我们import的模块都会从PYTHONPATH里面寻找。 |
PYTHONSTARTUP | Python启动后,先寻找PYTHONSTARTUP环境变量,然后执行此变量指定的文件中的代码。 |
PYTHONCASEOK | 加入PYTHONCASEOK的环境变量, 就会使python导入模块的时候不区分大小写. |
PYTHONHOME | 另一种模块搜索路径。它通常内嵌于的PYTHONSTARTUP或PYTHONPATH目录中,使得两个模块库更容易切换。 |
通常我们会在命令行上设置PYTHONPATH。在执行脚本之前先执行设置PYTHONPATH的命令。
例如windows上,设置PYTHONPATH的命令为:
[plain] view plain copy
- SET ROOT_DIR=%~dp0
- 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

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:
- [Right Click]Computer > Properties >Advanced System Settings > Environment Variables
- Click [New] under "System Variable"
- Variable Name: PY_HOME, Variable Value:C:\path\to\python\version
importError: No module named site - Click [OK]
- Locate the "Path" System variable and click [Edit]
-
Add the following to the existing variable:
%PY_HOME%;%PY_HOME%\Lib;%PY_HOME%\DLLs;%PY_HOME%\Lib\lib-tk;
importError: No module named site - 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.