使urllib与python 2和3一起工作的巧妙方法

 手机用户2502909797 发布于 2023-01-07 16:38

我正在寻找有关如何组合两个代码片段的建议,以便它们可以同时使用python 2和3.目标是使其"整洁",理想情况下将其保持为一行并限制任何if/else/try /除了结构.

对于python 3.x

   import xml.etree.ElementTree as ET, urllib.request, gzip, io
   url = "https://github.com/OpenExoplanetCatalogue/oec_gzip/raw/master/systems.xml.gz"
   oec = ET.parse(gzip.GzipFile(fileobj=io.BytesIO(urllib.request.urlopen(url).read())))

对于python 2.x

  import xml.etree.ElementTree as ET, urllib, gzip, io
  url = "https://github.com/OpenExoplanetCatalogue/oec_gzip/raw/master/systems.xml.gz"
  oec = ET.parse(gzip.GzipFile(fileobj=io.BytesIO(urllib.urlopen(url).read())))

Jon-Eric.. 10

这正是six为此创建的.它是一个允许你的代码同时使用Python 2和3的库.(不要让"库"吓到你,它只是一个.py文件,使它很容易集成/打包.)

您不必使用内置urllib模块,而是使用六个版本,它会自动重定向到Python 2和3中的内置模块.

这是您的代码的样子:

import xml.etree.ElementTree as ET, gzip, io
from six.moves.urllib.request import urlopen
url = "https://github.com/OpenExoplanetCatalogue/oec_gzip/raw/master/systems.xml.gz"
oec = ET.parse(gzip.GzipFile(fileobj=io.BytesIO(urlopen(url).read())))

请参阅:https://pythonhosted.org/six/#module-six.moves.urllib.request

2 个回答
  • 这正是six为此创建的.它是一个允许你的代码同时使用Python 2和3的库.(不要让"库"吓到你,它只是一个.py文件,使它很容易集成/打包.)

    您不必使用内置urllib模块,而是使用六个版本,它会自动重定向到Python 2和3中的内置模块.

    这是您的代码的样子:

    import xml.etree.ElementTree as ET, gzip, io
    from six.moves.urllib.request import urlopen
    url = "https://github.com/OpenExoplanetCatalogue/oec_gzip/raw/master/systems.xml.gz"
    oec = ET.parse(gzip.GzipFile(fileobj=io.BytesIO(urlopen(url).read())))
    

    请参阅:https://pythonhosted.org/six/#module-six.moves.urllib.request

    2023-01-07 16:41 回答
  • 如果你不想要额外的依赖,你可以简单地使用一个try except块来导入同一个别名下的模块...:

    try:
        import urllib.request as urlrequest
    except ImportError:
        import urllib as urlrequest
    
    url = "https://github.com/OpenExoplanetCatalogue/oec_gzip/raw/master/systems.xml.gz"
    oec = ET.parse(gzip.GzipFile(fileobj=io.BytesIO(urlrequest.urlopen(url).read())))
    

    2023-01-07 16:43 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有