Home > Net >  how to visualize the python venv name in MacOs zsh prompt
how to visualize the python venv name in MacOs zsh prompt

Time:08-20

enter image description hereI am just starting to learn django and I am facing the set-up phase. In particular I'd like to ask how to recognize if the virtual environment is activated or not. I know that I can use the command pip freeze but in all the tutorial that I am following, when the venv is activated, I can see the venv name in brackets in the terminal command line. I can correctly activate the venv with the source command and check via the pip freeze command but I have no indication in the command line. I am on a Mac/OS(M1) and using python3

thank you

CodePudding user response:

To have visual information about the virtualenv on the command line you need to change the shell config to show it. It's not related to python or django itself.

It will depend on the shell that you are using, but assuming the default shell on mac you can check this question virtualenv name not show in zsh prompt

CodePudding user response:

From venv docs.

When a virtual environment is active, the VIRTUAL_ENV environment variable is set to the path of the virtual environment. This can be used to check if one is running inside a virtual environment.

So you should be able to test it with:

import os

os.getenv('VIRTUAL_ENV') is not None

CodePudding user response:

Yes, when the virtual environment is activated, it shows in the terminal as a prefix like

(env) yourname~Desktop/workspace-folder> 

And that is enough to know it is activated, and you are using it.

Since you are using Python 3, you can create your virtual environment as follows in the same directory of your project, open terminal or iTerm and run this comman

python3 -m venv env

After few seconds, a folder env will be created that is your virtual environment. Note you can name your virtual environment as you wish, maybe like python3 -m venv djang-app

After you have created the virtual environment, you can now activate it like

source env/bin/activate

Again, if you created your virtual environment using lets say django-app

python3 -m venv django-app

You can activate it like this

source django-app/bin/activate

and you will see your terminal is prefixed as follows

(django-app) yourname~Desktop/workspace-folder> 

To deactivate the virtual environment, you simply run this command deactivate in the terminal with active virtual environment.

You can learn more about python3 venv from here.

  • Related