为什么`sys.path`在mod_wsgi和普通解释器模式下执行时有所不同?

时间:2017-05-30 06:19:48

标签: python apache python-2.7 mod-wsgi

环境: MAC OS 10.10.4 python 2.7.12 with pyenv mod_wsgi 3.4 Apache/2.4.10 (Unix)

我有一个打印sys.path的wsgi.py:

import sys
print sys.path
sys.path.insert(0, '...')

from app import app as application

我确认在安装mod_wsgi期间,它配置了正确的python版本( /Users/forever/.pyenv/shims/python :由pyenv安装):

checking for apxs2... no
checking for apxs... /usr/sbin/apxs
checking Apache version... 2.4.10
checking for python... /Users/forever/.pyenv/shims/python
configure: creating ./config.status
config.status: creating Makefile

然后使用以下内容配置Apache:

<VirtualHost *:5000>
    ServerName loyal.jms.tw

    # WSGIPythonHome /Users/forever/.pyenv/shims
    WSGIDaemonProcess test user=forever group=admin threads=5
    WSGIScriptAlias / /Users/forever/git/test/app/wsgi.py

    <Directory /Users/forever/git/test/app>
        WSGIProcessGroup test
        WSGIApplicationGroup %{GLOBAL}
        Order deny,allow
        Allow from all
    </Directory>
</VirtualHost>

Apache日志显示配置了正确python版本的mod_wsgi信息:

[Tue May 30 13:59:28.658723 2017] [mpm_prefork:notice] [pid 4843] AH00163: Apache/2.4.10 (Unix) PHP/5.5.24 mod_wsgi/3.4 Python/2.7.12 configured -- resuming normal operations

然后奇怪的部分是Apache日志中的sys.path输出:

['/usr/lib/python27.zip', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-darwin', '/usr/lib/python2.7/plat-mac', '/usr/lib/python2.7/plat-mac/lib-scriptpackages', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/Library/Python/2.7/site-packages']

这似乎是系统默认python的python路径,而不是我pyenv安装的python。然后我检查sys.pathpyenv安装的python解释器的关系,它显示:

Python 2.7.12 (default, May 26 2017, 21:30:36)
[GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.72)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/Users/forever/.pyenv/versions/2.7.12/lib/python27.zip', '/Users/forever/.pyenv/versions/2.7.12/lib/python2.7', '/Users/forever/.pyenv/versions/2.7.12/lib/python2.7/plat-darwin', '/Users/forever/.pyenv/versions/2.7.12/lib/python2.7/plat-mac', '/Users/forever/.pyenv/versions/2.7.12/lib/python2.7/plat-mac/lib-scriptpackages', '/Users/forever/.pyenv/versions/2.7.12/lib/python2.7/lib-tk', '/Users/forever/.pyenv/versions/2.7.12/lib/python2.7/lib-old', '/Users/forever/.pyenv/versions/2.7.12/lib/python2.7/lib-dynload', '/Users/forever/.pyenv/versions/2.7.12/lib/python2.7/site-packages']

,这是不同的。

我想知道这怎么可能发生?以及如何更正mod_wsgi使用的python路径?

1 个答案:

答案 0 :(得分:0)

WSGI尚未配置为使用您的virtualenv Python。见documentation on WSGI and virtualenv;您需要配置守护进程组以使用正确的二进制文件:

# add the python-home argument here
WSGIDaemonProcess test python-home=/Users/forever/.pyenv/shims user=forever group=admin threads=5

否则,正如文档所述:

  

由于只在守护进程组中运行单个应用程序,因此也使用WSGIApplicationGroup指令。 当它与%{GLOBAL}值一起使用时,它会强制WSGI应用程序在每个进程的主Python解释器上下文中运行。

大胆强调我的。

WSGIPythonHome应仅用于嵌入模式(无WSGIDaemonProcessWSGIProcessGroup指令)。