Apache2 / Python CGI:网页访问时ImportError,命令行正常

0 投票
1 回答
510 浏览
提问于 2025-04-18 18:31

我有一个Python的CGI脚本,想在共享主机上运行cv2.py。命令行里一切都正常,但一到CGI就出现了导入错误,找不到cv2。

这个Apache的安装有点特别,因为我的Python版本是2.7.2,但这并不是默认的Python版本,而且所有的库都是安装在我个人的主目录下。

这是代码:

#!/path/to/bin/python
import cgi
import cgitb
import sys
version = sys.version
cgitb.enable()
path = sys.path
import os
import pwd
# import cv2  << this is the line that causes the error from the web

def get_username():
    return pwd.getpwuid( os.getuid() )[ 0 ]
print "Content-Type: text/html"
print
print "<h1>%s</h1>" % version
print "<h1>%s</h1>" % path
print "<h1>%s</h1>" % get_username()

最奇怪的是,从网页服务器上运行的用户名、路径和版本,跟命令行里的一模一样。在命令行里,cv2可以正常导入和使用,但在网页上,同样的文件却在导入cv2时出现了导入错误:

    cv2 undefined
<type 'exceptions.ImportError'>: numpy.core.multiarray failed to import 
      args = ('numpy.core.multiarray failed to import',) 
      message = 'numpy.core.multiarray failed to import'

如果我尝试导入numpy或者Image(PIL),我反而会遇到内存错误:

<type 'exceptions.MemoryError'>: 
  args = () 
  message = ''

我在想,是否还有其他可能的配置问题会导致网页服务器出现导入错误,而命令行里一切正常,并且看起来配置也完全一样?

1 个回答

0

我对内存错误做了一些深入的搜索,发现了一个不太常见的解决办法,就是修改ctypes/init.py,这个方法在这种情况下似乎有效:

https://stackoverflow.com/a/6769624/895656

看起来这是numpy 1.8.2版本中的一个bug。

撰写回答