pythonpython-3.xubuntusyntax-errorvirtualenv

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(), filename, 'exec'), globals, locals)
print(os.system('pwd'))

if hasattr(sys, 'real_prefix'):
    print('success')
else:
    print('failed')

I then run this script via the terminal:

python Test.py

which then produces this error:

Traceback (most recent call last): File "activate_this.py", line 3, in <module> exec(compile(open(filename, "rb").read(), filename, 'exec'), globals, locals) File "activate", line 4 deactivate () { ^ SyntaxError: invalid syntax


I can activate the virtualenv successfully by executing cd env/bin and then source activate


TLDR

Activating virtualenv from python script is throwing a syntax error from within the activate file.


Solution

  • The very 1st 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.Docs]: Built-in Functions - 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.Docs]: 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)
    

    Might be related: