Skip to content Skip to sidebar Skip to footer

Activating Virtualenv From Within Python Script

I am trying to activate my virtualenv (already existing) using the following python code: Test.py import os, sys filename = 'activate' exec(compile(open(filename, 'rb').read(), fil

Solution 1:

The very 1 line of activate (note that VEnv is installed on Win, but this shouldn't be a problem):

# This file must be used with "source bin/activate" *from bash* 

That, and the lines below should tell you that activate is a (Bourne) shell file.

[Python 3]: compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) on the other hand, works with Python source code.

So, in order to execute the file, you'd need to use other ways, e.g. [Python 3]: subprocess - Subprocess management. You can check how I've used it: [SO]: How to effectively convert a POSIX path to Windows path with Python in Cygwin? (@CristiFati's answer).

But, I really don't see the point of doing all this, you probably misunderstood your colleague's suggestion. Also note that even if you do manage to do it this way, all the environment variables will only be set in the calling process, so it will pretty much be unusable (well, unless you also execute your script from there too).

You should go the recommended way ([PyPA]: Virtualenv - User Guide), and that is (from bash):

source /path/to/Django/ENV/bin/activate
python your_project_startup_script.py  # (as I recall, it's manage.py)

Post a Comment for "Activating Virtualenv From Within Python Script"