1

我刚刚开始使用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 进程或重新加载模块:”(从这里)。

有谁知道这样做的正确方法?

4

1 回答 1

5

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

长答案...

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

sys.path主要由静态定义填充,包括 C:\Python26\Lib\ 和PYTHONPATH环境变量。但是,还有一件额外的事情值得了解。当你运行“python”时,当前工作目录被添加到sys.path. 当你运行“python C:\foo\bar\baz.py”时,C:\foo\bar\' is added to the front ofsys.path . But when you run "twistd ...", nothing useful is added tosys.path`。

This last behavior probably explains why your tests work if you run the rpy script directly, or if you run python and try to import the module interactively, but fail when you use twistd. Adding C:\py\twisted to the PYTHONPATH environment variable should make the module importable when the rpy script is run from the server you start with twistd.

于 2010-05-15T01:41:42.743 回答