115

我正在尝试添加 PYTHONPATH 环境变量的路径,该路径仅在特定的 virtualenv 环境中可见。

我在 virtualenv 命令提示符下尝试过SET PYTHONPATH=...,但这会为整个环境设置变量。

我该如何做到这一点?

4

6 回答 6

175

您通常可以通过使用.pthfiles来避免对 PYTHONPATH 做任何事情。只需在您的 virtualenv 的 site-packages 文件夹中放置一个扩展名为 .pth 的文件(任何基本名称都可以),例如lib\python2.7\site-packages,将包含您的包的目录的绝对路径作为其唯一内容。

于 2012-05-24T14:47:30.150 回答
93
于 2013-03-07T22:23:26.407 回答
5

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.

于 2016-05-09T12:49:50.590 回答
3

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

于 2019-02-27T18:20:45.080 回答
1
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.

于 2018-03-01T09:45:32.213 回答
0

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.

于 2021-06-16T03:24:40.397 回答