且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

运行脚本时自动加载 virtualenv

更新时间:2023-12-04 19:39:04

有两种方法可以做到:

  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.