从 Python 脚本中激活 virtualenv [英] Activating virtualenv from within Python script

查看:45
本文介绍了从 Python 脚本中激活 virtualenv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下 python 代码激活我的 virtualenv(已经存在):

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

然后产生这个错误:

回溯(最近一次调用最后一次):文件activate_this.py",第 3 行,在 <module> 中exec(compile(open(filename, "rb").read(), filename, 'exec'), globals, locals)文件激活",第 4 行停用(){^语法错误:无效语法

我可以通过执行cd env/bin然后source activate

TLDR

从 python 脚本激活 virtualenv 会在激活文件中引发语法错误.

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

推荐答案

activate 的第一行st(注意 VEnv 是安装在 Win 上,但这应该不是问题):

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* 

那个,下面的几行应该告诉你 activate 是一个 (Bourne) shell 文件.

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

[Python 3]:编译(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) 另一方面,适用于 Python 源代码.

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

因此,为了执行文件,您需要使用其他方式,例如[Python 3]:子流程 - 子流程管理.
您可以查看我是如何使用它的:[SO]:如何在 Cygwin 中使用 Python 有效地将 POSIX 路径转换为 ​​Windows 路径?(@CristiFati 的回答).

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

你应该采用推荐的方式([PyPA]: Virtualenv - User指南),即(来自bash):

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)

这篇关于从 Python 脚本中激活 virtualenv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆