简体   繁体   中英

How do I add a path to PYTHONPATH in virtualenv

I am trying to add a path to the PYTHONPATH environment variable, that would be only visible from a particular virtualenv environment.

I tried SET PYTHONPATH=... under a virtualenv command prompt, but that sets the variable for the whole environment.

How do I achieve that?

You can usually avoid having to do anything with PYTHONPATH by using .pth files . Just put a file with a .pth extension (any basename works) in your virtualenv's site-packages folder, eg lib\\python2.7\\site-packages , with the absolute path to the directory containing your package as its only contents.

如果您使用的是virtualenv ,您可能也应该使用virtualenvwrapper ,在这种情况下,您可以使用add2virtualenv命令将路径添加到当前 virtualenv 的 Python 路径:

add2virtualenv directory1 directory2 …

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM