1

我有运行 Python 程序的 bash 脚本。我使用虚拟环境。

首先我将 env 包括在 bash 中:

source ./ENV/bin/activate

然后我在 bash 提示符中看到 (ENV) 前缀。

$ echo $PATH
/project/ENV/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/usr/bin/core_perl

当我尝试从 bash 脚本运行我的 Python 程序时,它运行的 Python 版本错误。ENV 使用 Python 2.6,而系统默认使用 3.2。

我从 Python 脚本打印 Python 版本,它打印 3。

但为什么?

ls -la
-rw-r--r-- 1 wnc wnc 2219 Sep 27 01:42 activate
-rw-r--r-- 1 wnc wnc 1275 Sep 27 01:42 activate.csh
-rw-r--r-- 1 wnc wnc 2414 Sep 27 01:42 activate.fish
-rw-r--r-- 1 wnc wnc 1129 Sep 27 01:42 activate_this.py
-rwxr-xr-x 1 wnc wnc 357 Sep 27 01:42 easy_install
-rwxr-xr-x 1 wnc wnc 365 Sep 27 01:42 easy_install-2.6
-rwxr-xr-x 1 wnc wnc 318 Sep 27 01:42 pip
-rwxr-xr-x 1 wnc wnc 326 Sep 27 01:42 pip-2.6
lrwxrwxrwx 1 wnc wnc 9 Sep 27 01:42 python -> python2.6 
lrwxrwxrwx 1 wnc wnc 9 Sep 27 01:42 python2 -> python2.6
-rwxr-xr-x 1 wnc wnc 6240 Sep 27 01:42 python2.6
4

1 回答 1

1

Sanity check:

source /path/to/ENV/bin/activate
python -V
deactivate
python -V

The first python -V should show print Python 2.6 and the second Python 3.2, right?

When you run your Python script, the one you want to use the above virtualenv, make sure to source /path/to/ENV/bin/activate first, for example if you run it from inside a bash script:

#!/bin/bash
source /path/to/ENV/bin/activate
python /path/to/script.py

Tell me which step doesn't work and any error messages you get.

If your python program needs to run in a different way, not from a shell script, for example by wsgi, then I'll have more tips for you. The bottom line is: don't forget to source the virtualenv activate script before using your python script that needs it.

于 2013-10-07T06:34:04.387 回答