【问题标题】:Can't "import urllib.request, urllib.parse, urllib.error"不能“导入 urllib.request、urllib.parse、urllib.error”
【发布时间】:2016-09-18 15:31:55
【问题描述】:

我试图将我的项目转换为 python3。

我的服务器脚本是 server.py:

#!/usr/bin/env python
#-*-coding:utf8-*-

import http.server
import os, sys
server = http.server.HTTPServer
handler = http.server.CGIHTTPRequestHandler
server_address = ("", 8080)
#handler.cgi_directories = [""]
httpd = server(server_address, handler)
httpd.serve_forever()

但是当我尝试时:

import urllib.request, urllib.parse, urllib.error

我在 python3 ./server.py 的终端中得到这个:

    import urllib.request, urllib.parse, urllib.error
ImportError: No module named request
127.0.0.1 - - [18/Sep/2016 22:47:18] CGI script exit status 0x100

我该怎么做?

【问题讨论】:

  • 您确定要在 Python 3 而不是 Python 2 中运行该代码吗?
  • 只是为了检查 - python3 -V 显示什么?
  • 对不起。我犯了一个错误。我运行'python3 ./server.py',但我在使用 python2 的编辑器上进行了测试。
  • 但是python3服务器上仍然存在问题:导入urllib.request,urllib.parse,urllib.error ImportError:没有名为request 127.0.0.1的模块 - - [18/Sep/2016 22:47:18 ] CGI 脚本退出状态 0x100
  • 太复杂了!我运行 python3 ./server.py。但是当我在 cgi 脚本 'print(sys.version)' 中使用 python3 语法时,我得到了 '2.7.12 (default, Jul 1 2016, 15:12:24) [GCC 5.4.0 20160609]' ?!?!?

标签: python python-2.7 python-3.x urllib


【解决方案1】:

您的 shebang 建议代码应该由 python 二进制文件运行,这在历史上与 Python 2.x 版本相关。

只需将第一行更改为:

#!/usr/bin/env python3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-29
    • 2015-10-06
    • 1970-01-01
    • 2014-10-04
    • 2013-03-27
    • 2016-01-17
    • 2021-02-12
    • 1970-01-01
    相关资源
    最近更新 更多