Activate virtualenv using alias

3

1

I can activate my python virtual environment from it's folder by entering . bin/activate. I'd like to instead type a single word alias, such as shazam, from the home folder (or anywhere else) that activates the environment, changes to my master project folder, and lists my projects.

I tried creating an alias in .bashrc that pointed to an .sh file containing:

cd ~/path-to-virtual-environment
. bin/activate
cd ~/path-to-master-project-folder
ls -a

I was getting a permission denied error, so I ran chmod u+x <script file>. The script now runs, but the VE does not activate and while the project folders are listed, the shell is not in the master project folder. I would appreciate some guidance. Thanks.

NOTE: I received an ANSWER on another forum. Shell scripts do not change the environment from which they're called; instead, use a shell function inside .bashrc.

shazam () {
  source ~/path-to-virtual-environment/bin/activate
  cd ~/path-to-master-project-folder
  ls -a
}

landrykid

Posted 2017-12-31T07:42:13.677

Reputation: 31

Answers

1

Alias can have list of commands:

alias shazm='source ~/path-to-virtual-environment/bin/activate; cd ~/path-to-master-project-folder; ls -a'

Tomasz Jakub Rup

Posted 2017-12-31T07:42:13.677

Reputation: 598

0

This is a core feature of the virtualenvwrapper package, along with a robust, complementary featureset.

To create a virtualenv named shazam using virtualenvwrapper, simply:

mkvirtualenv shazam

To activate it:

workon shazam

To deactivate it, like any active virtualenv:

deactivate

Many use-cases and user configurations are possible using virtualenvwrapper. For instance, I prefer to keep all my virtualenvs in a single directory, ~/.envs. This is supported as a configuration. It's an open source and actively maintained project, I can't recommend it strongly enough.

Stew

Posted 2017-12-31T07:42:13.677

Reputation: 990