运行脚本时自动加载 virtualenv [英] Automatically load a virtualenv when running a script

查看:47
本文介绍了运行脚本时自动加载 virtualenv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要来自 virtualenv 的依赖项的 python 脚本.我想知道是否有某种方法可以将它添加到我的路径中并让它自动启动它的 virtualenv,运行然后返回到系统的 python.

I have a python script that needs dependencies from a virtualenv. I was wondering if there was some way I could add it to my path and have it auto start it's virtualenv, run and then go back to the system's python.

我尝试过使用 autoenv 和 .env 但这似乎并没有完全满足我的要求.我还考虑过将 shabang 更改为指向 virtualenv 路径,但这似乎很脆弱.

I've try playing around with autoenv and .env but that doesn't seem to do exactly what I'm looking for. I also thought about changing the shabang to point to the virtualenv path but that seems fragile.

推荐答案

有两种方法可以做到:

  1. 将虚拟环境 python 的名称放入脚本的第一行.像这样

  1. Put the name of the virtual env python into first line of the script. Like this

#!/your/virtual/env/path/bin/python

#!/your/virtual/env/path/bin/python

将虚拟环境目录添加到 sys.path.请注意,您需要导入 sys 库.像这样

Add virtual environment directories to the sys.path. Note that you need to import sys library. Like this

导入系统

sys.path.append('/path/to/virtual/env/lib')

sys.path.append('/path/to/virtual/env/lib')

如果您选择第二个选项,您可能需要向 sys.path(站点等)添加多个路径.获得它的最好方法是运行你的虚拟环境 python 解释器并找出 sys.path 值.像这样:

If you go with the second option you might need to add multiple paths to the sys.path (site etc). The best way to get it is to run your virtual env python interpreter and fish out the sys.path value. Like this:

/your/virtual/env/bin/python

Python blah blah blah

> import sys
> print sys.path
[ 'blah', 'blah' , 'blah' ]

将 sys.path 的值复制到上面的代码段中.

Copy the value of sys.path into the snippet above.

这篇关于运行脚本时自动加载 virtualenv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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