代码之家  ›  专栏  ›  技术社区  ›  Carson Myers

twisted.web服务器的导入问题

  •  1
  • Carson Myers  · 技术社区  · 15 年前

    我刚开始使用twisted.web,在将Python模块导入到 .rpy 脚本。

    在里面 C:\py\twisted\mysite.py 我有这个:

    from twisted.web.resource import Resource
    from twisted.web import server
    
    class MySite(Resource):
        def render_GET(self, request):
            request.write("<!DOCTYPE html>")
            request.write("<html><head>")
            request.write("<title>Twisted Driven Site</title>")
            request.write("</head><body>")
            request.write("<h1>Twisted Driven Website</h1>")
            request.write("<p>Prepath: <pre>{0}</pre></p>".format(request.prepath))
            request.write("</body></html>")
            request.finish()
            return server.NOT_DONE_YET
    

    而在 C:\py\twisted\index.rpy 我有这个:

    import mysite
    reload(mysite)
    
    resource = mysite.MySite()
    

    我跑 twistd -n web --port 8888 --path C:\py\twisted 在命令提示下,服务器成功启动。但当我要求的时候 localhost:8888 我得到了一个(巨大的)源于importError的堆栈跟踪:

    <type 'exceptions.ImportError'>: No module named mysite

    我可以从解释器导入模块,如果我只是执行 index.rpy 作为一个python脚本,我不会得到导入错误。关于这个主题的文档有点含糊不清,它只是说“然而,在Python模块中定义资源子类通常是一个更好的主意。为了使模块中的更改可见,必须重新启动python进程,或重新加载模块:“(从 here )

    有人知道怎么做吗?

    1 回复  |  直到 15 年前
        1
  •  5
  •   Jean-Paul Calderone    15 年前

    简短回答:您需要将pythonpath设置为包括 C:\py\twisted .

    长回答…

    一个RPY脚本 基本上只是一些Python代码,就像其他任何Python代码一样。因此,RPY脚本中的导入操作与任何其他Python代码中的导入操作一样。对于最常见的情况,这意味着 sys.path 按顺序逐个访问,如果 .py 找到与导入名称匹配的文件,该文件用于定义模块。

    搜索路径 主要由静态定义填充,包括c:\python26\lib\和 PYTHONPATH 环境变量。不过,还有一件事值得了解。运行“python”时,当前工作目录将添加到 搜索路径 . 运行“python c:\foo\bar\baz.py”时, C:\foo\bar\' is added to the front of 搜索路径 . But when you run "twistd ...", nothing useful is added to 系统路径。

    最后一个行为可能解释了如果直接运行RPY脚本,或者运行python并尝试交互导入模块,但使用twisted时失败的原因。添加 c:\pY-扭曲 Python路径 当从以twisted开头的服务器运行rpy脚本时,环境变量应该使模块可导入。