user3630290
user3630290

Reputation: 47

How to switch virtualenv in shell script?

For my personal project, I'm trying to analyze the technical debt of various python libraries. For this, I made python script which downloads the library, checks out to each merged commit and runs the analysis. One part of the analysis is to get the test coverage.

The easiest way I found to get it is to run

coverage run --source={library}/ setup.py test

However, I want to have this automated so I'm trying to run this command in a shell script from the python script mentioned above.

The script shall change the dir to the library, switch to virtualenv (automatically created in the previous steps of the analysis) and run the coverage. However, it fails on Requirement error which indicates that it does not actually switch the virtualenv and stays in the virtualenv of the analysis project.

The shell script looks like this:

#!/usr/bin/env bash

# Args
# $1 proj_path
# $2 proj_name
# $3 venv_name

cd $1
source `which virtualenvwrapper.sh`
workon $3
coverage run --source=$2/ setup.py test
coverage report

And it's called from the python script like this:

subprocess.call(["analyzer/run_coverage.sh", self.repo_path, self.repo_name, self.venv_name])

Could you please help me how to switch the venv in the shell script? Thanks!

Upvotes: 0

Views: 1807

Answers (1)

gbajson
gbajson

Reputation: 1740

Script 'activate' activates virtual env, and 'deactivate' deactivates virtual env:

https://virtualenv.pypa.io/en/stable/userguide/

Example of the loop over two virtual environments stored in bash array:

venvs=(~/venvs/py3.6.4 ~/venvs/py3.7.0)
$ for i in "${venvs[@]}"
do
  source "$i"/bin/activate
  which python
  python --version
  deactivate
done
/home/gbajson/venvs/py3.6.4/bin/python
Python 3.6.4
/home/gbajson/venvs/py3.7.0/bin/python
Python 3.7.0

Upvotes: 1

Related Questions