从其他脚本导入代码时出现Python错误500

2024-05-08 00:59:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个很奇怪的问题。 当我从linux命令行python scriptname.py运行这个脚本时,一切正常。当我通过浏览器请求它时,它会给我内部错误500

我正在导入脚本列车状态.py在我运行的脚本的同一目录中。我还在目录中放置了一个具有777权限的空文件__init__.py

注意:任何执行标准导入(例如import os)的脚本都可以通过浏览器正常工作

from trainstate import *

print "Content-Type: text/html\n\n"

st = TrainState(784)
print st.get_state()

我做错什么了?你知道吗


Tags: 文件命令行pyimport目录脚本权限linux
2条回答

I am importing a script trainstate.py which is in the same directory of the script I am running

这并不意味着这个目录是您的web服务器进程的当前工作目录,也不意味着它在系统路径对于这个过程。thkang已经提供了最好的答案(我应该说的是相反的顺序),但是无论如何-试着用这个代码来代替,看看你得到了什么:

import sys, os
print "Content-Type: text/html\n\n"

print "sys.path is : ", ", ".join(sys.path)
print "current working directory is : ", os.getcwd()

try: 
    # star imports are evil
    from trainstate import TrainState
except Exception, e:
    print "failed to import TrainState : %s" % e
else: 
    st = TrainState(784)
    print st.get_state()

在你的补充意见之后,我想详细说明一下。你知道吗

您可能正在使用一些不是python的参考cgi/http/wsgi实现的cgi后端。相反,这个后端(不管是apache、iis还是其他什么)可能会嵌入一个python解释器来运行python cgi脚本。你知道吗

我在此设置中遇到的最常见的问题之一是处理导入路径。考虑以下场景:

  1. 我有foo.py公司以及棒.py在同一个目录中。你知道吗
  2. 你知道吗foo.py公司是cgi的入口点。你知道吗
  3. 你知道吗foo.py公司进口棒.pyimport bar做某事。你知道吗
  4. 不知怎的导入失败了。你知道吗
  5. 这是非常令人沮丧的,因为我们别无选择,只能盯着丑陋的粗体信息。你知道吗

这是因为foo.py公司不包含在pythonpath中,与运行时不同foo.py公司从命令行。要解决这个问题,可以将其路径添加到sys.path。你知道吗

所以,解决方案是:

import os
import sys
current_path = os.path.dirname(__file__)
sys.path.insert(0, current_path)

... rest of the script

好吧,如果你有列车状态.py在某个单独的文件夹中,必须在sys.path中添加该文件夹的路径。你知道吗

相关问题 更多 >