使用py2exe构建Python时出现导入错误

3

我正在尝试编写一个小脚本来远程管理Windows计算机(目前只能关机)。我使用的方法涉及webapp2服务器。我想将我的第一次尝试编译成 .exe 文件。问题在于,成功编译后运行它时会返回错误:

Traceback (most recent call last):
 File "web2.py", line 2, in <module>
 File "webapp2.pyc", line 25, in <module>
 File "webob\__init__.pyc", line 1, in <module>
 File "webob\datetime_utils.pyc", line 10, in <module>
ImportError: No module named email.utils

我也尝试过使用cx_Freeze,结果类似。我按照import error while bundling using py2exe中给出的建议进行了操作,但无济于事。
如果有用的话,这是我的代码:
import cgi
import webapp2
import os
import socket


def ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(('google.com', 0))
    return s.getsockname()[0]

class MainPage(webapp2.RequestHandler):
    def get(self):
        self.response.out.write("""
          <html>
            <body>
              <form action="/shutdown" method="link">
                <div><input type="submit" value="Shutdown"></div>
              </form>
            </body>
          </html>""")


class shutdown(webapp2.RequestHandler):
    def get(self):
        self.response.out.write('<html><body>Shutting down...<pre>')
        self.response.out.write('</pre></body></html>')
        os.system("shutdown -p -f")

app = webapp2.WSGIApplication([('/', MainPage),
                              ('/shutdown', shutdown)],
                              debug=True)
def main():
    from paste import httpserver
    httpserver.serve(app, host=ip(), port='80')

if __name__ == '__main__':
    main()

感谢您的提前帮助。
编辑:
我使用 modulefinder 发现有很多模块没有被导入。然而,我不知道这是在正常运行时发生还是仅在导入时发生或类似情况。 http://pastebin.com/s0U9WHJ6

如果您在代码中添加 import email.utils 并使用 py2exe 重新生成 .exe 文件,这是否有帮助? - Luke Woodward
谢谢,我尝试了这个方法,但是还是得到了完全相同的错误。 - user1492867
嗯...奇怪。如果您在不使用py2exe的情况下运行脚本,是否会出现相同的错误?有趣的是,datetime_utils模块使用了已经过时一段时间的rfc822模块。然而,我不知道这有多大关联。 - Luke Woodward
不,如果不使用py2exe,我就不会出现错误。 - user1492867
2个回答

0

我发现问题在于我假定py2exe会像解释器一样导入webob。实际上,我需要将webob文件夹放在我构建的文件夹中。


0

我不确定,但你可以尝试在导入py2exe的脚本中,在setup函数调用中添加以下参数,特别包含email.utils:

options={"py2exe": {'includes': ["email.utils"]}}

那么,或者你可以在导入webapp2之前尝试特定地导入它,就像第1行一样:
import email.utils
import cgi
import webapp2

如果出现找不到其他模块的情况,请尝试将该模块添加到包含列表中:
options={"py2exe": {'includes': ["email.utils", "othermodulename"]}}

或者具体地再次导入它。 希望这可以帮到你!:-)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接