Activating virtualenv from within Python script

不羁的心 提交于 2019-12-13 18:49:51

问题


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.


回答1:


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 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)


来源:https://stackoverflow.com/questions/54420483/activating-virtualenv-from-within-python-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!