Sasha Ahrestani
Sasha Ahrestani

Reputation: 87

How to use virtualenv in Python project?

I'm trying to use virtualenv in my new mainly Python project. The code files are located at ~/Documents/Project, and I installed a virtual environment in there, located at ~/Documents/Project/env. I have all my packages and libraries I wanted in the env/bin folder.

The question is, how do I actually run my Python scripts, using this virtual environment? I activate it in Terminal, then open idle as a test, and try

"import django"

but it doesn't work. Basically, how can I use the libraries install in the virtual environment with my project when I run it, instead of it using the standard directories for installed Python libraries?

Upvotes: 0

Views: 2251

Answers (2)

abehrens
abehrens

Reputation: 185

It's also good practice to make a requires.txt file for all your dependencies. If for example your project requires Flask and pymongo, create a file with:

Flask==<version number you want here> pymongo==<version number you want here>

Then you can install all the necessary libraries by doing:

pip install -r requires.txt

Great if you want to share your project or don't want to remember every library you need in your virtualenv.

Upvotes: 0

clocker
clocker

Reputation: 1366

Check out the example below, and also the virtualenv documentation. It's actually fairly straightforward if you follow the steps:

virtualenv Project  # creates a new Project dir
cd Project/bin      # could just call Project/bin
. activate          # should now have (Project) in the prompt name
pip install django  # without this, won't be able to import django
deactivate          # switch of virtual mode 

I tried the above out in my Mac and worked fine. Here's a transcript for reference.

Transcript of operations

[MacMini]<Documents> :virtualenv Project

[MacMini]<Project> :cd bin/

[MacMini]<bin> :python2.7
Python 2.7.9 (v2.7.9:648dcafa7e5f, Dec 10 2014, 10:10:46)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named django
>>> quit()

[MacMini]<bin> :. activate

(Project)[MacMini]<bin> :pip install django
You are using pip version 6.0.6, however version 8.1.0 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
Collecting django
  Downloading Django-1.9.4-py2.py3-none-any.whl (6.6MB)
    100% |################################| 6.6MB 1.2MB/s
Installing collected packages: django

Successfully installed django-1.9.4

(Project)[MacMini]<bin> :python
Python 2.7.10 (default, Oct 23 2015, 18:05:06)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.59.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> quit()

(Project)[MacMini]<bin> :deactivate

Upvotes: 2

Related Questions