How to activate/deactivate a virtualenv from python code?

主宰稳场 提交于 2021-02-16 15:58:16

问题


For activation there is a script that activates a virtualenv from an already running python interpeter using execfile('C:/path/to/virtualev/Scripts/activate_this.py', dict(__file__='C:/path/to/virtualev/Scripts/activate_this.py')). However since I can still import packages that are not in the virtualenv from the current python script I am confused about how it works.
For deactivation there is no python script at all.
What should I do?


回答1:


From part of the VirtualEnv homepage.

You must use the custom Python interpreter to install libraries. But to use libraries, you just have to be sure the path is correct. A script is available to correct the path. You can setup the environment like:

activate_this = '/path/to/env/bin/activate_this.py'
execfile(activate_this, dict(__file__=activate_this))



回答2:


If you want to run a program outside of the virtualenv, just run your system python executable (e.g. /usr/bin/python) instead of the one in the virtualenv.




回答3:


This souds like bad idea. You are trying to modify environment of your script within this script. Please explain why?

Can't you do it hierarchical? Use one script to run different scripts in different virtualenvs.




回答4:


at the command line, type the word 'deactivate'



来源:https://stackoverflow.com/questions/11573261/how-to-activate-deactivate-a-virtualenv-from-python-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!