我正在尝试添加 PYTHONPATH 环境变量的路径,该路径仅在特定的 virtualenv 环境中可见。
我在 virtualenv 命令提示符下尝试过SET PYTHONPATH=...
,但这会为整个环境设置变量。
我该如何做到这一点?
我正在尝试添加 PYTHONPATH 环境变量的路径,该路径仅在特定的 virtualenv 环境中可见。
我在 virtualenv 命令提示符下尝试过SET PYTHONPATH=...
,但这会为整个环境设置变量。
我该如何做到这一点?
您通常可以通过使用.pth
files来避免对 PYTHONPATH 做任何事情。只需在您的 virtualenv 的 site-packages 文件夹中放置一个扩展名为 .pth 的文件(任何基本名称都可以),例如lib\python2.7\site-packages
,将包含您的包的目录的绝对路径作为其唯一内容。
You can also try to put symlink to one of your virtualenv.
eg. 1) activate your virtualenv 2) run python 3) import sys and check sys.path 4) you will find python search path there. Choose one of those (eg. site-packages) 5) go there and create symlink to your package like: ln -s path-to-your-package name-with-which-you'll-be-importing
That way you should be able to import it even without activating your virtualenv. Simply try: path-to-your-virtualenv-folder/bin/python and import your package.
If you are using virtualenvwrapper,
$ cd to the parent folder
$ add2virtualenv folder_to_add
console will display
Warning: Converting "folder_to_add" to "/absoutle/path/to/folder_to_add"
That's it, and you should be good to go
import sys
import os
print(str(sys.path))
dir_path = os.path.dirname(os.path.realpath(__file__))
print("current working dir: %s" % dir_path)
sys.path.insert(0, dir_path)
I strongly suggest you use virtualenv and virtualenvwrapper to avoid cluttering the path.
As suggested by @crimeminister above, you can use virtualenvwrapper
then add2virtualenv
like suggested by @Aneesh Panoli. If add2virtualenv
is not working after pip install virtualenvwrapper
, then follow instructions in the top voted answer by @chirinosky here. Works for me.