Sunday, February 4, 2018

Getting Started with Python's Virtualenv

This blog will teach you how to get started with virtualenv in Python. First install virtualenv if you have not installed it.
pip install virtualenv
Create a new virtualenv directory called hello.
virtualenv hello
The above command will a standard Python installation.
hello/
├── bin
├── include
├── lib
└── pip-selfcheck.json

To activate the virtualenv we just created, we need to source the activate script in the bin directory. Once we are in the virtualenv environment, we can install any Python libraries we want and the libraries will be installed in the hello virtualenv we just created, e.g.
cd hello
source bin/activate
pip install requests
To quit the virtualenv, simply type
deactivate
Let's now create a simple script that uses the new request module we just installed.
test.py
import requests

if __name__ == '__main__':
    r = requests.get('http://www.google.com')
    print(r.status_code)
To run the script in a virtualenv.
cd hello
source bin/activate
python test.py
deactivate

No comments:

Post a Comment