推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
jeblur
V2EX  ›  Python

py2->py3 怎么转呀

  •  
  •   jeblur · Apr 9, 2020 · 4089 views
    This topic created in 2404 days ago, the information mentioned may be changed or developed.
    import socket
      
    target_host = "cn.bing.com"
    target_port = 80
    
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    client.connect((target_host,target_port))
    
    client.send("GET / HTTP/1.1\r\nHost:cn.bing.com\r\n\r\n")
    
    response = client.recv(4096)
    
    print(response)
    

    TypeError: a bytes-like object is required, not 'str'

    python 初学者,错误提示是需要把 str encode 到字节流:

    但是还是不知道怎么做才好。。

    烦请 v 友指点下,谢谢!

    8 replies  •  2020-04-09 17:56:47 +08:00
    maltoze
    maltoze
    Apr 9, 2020❤️2
    1
    client.send(b"GET / HTTP/1.1\r\nHost:cn.bing.com\r\n\r\n")
    Mithrandir
    Mithrandir
    Apr 9, 2020
    2
    man 2to3
    mns
    mns
    Apr 9, 2020
    3
    "GET / HTTP/1.1\r\nHost:cn.bing.com\r\n\r\n"
    改成
    b"GET / HTTP/1.1\r\nHost:cn.bing.com\r\n\r\n"
    gimp
    gimp
    Apr 9, 2020
    4
    str_data = "GET / HTTP/1.1\r\nHost:cn.bing.com\r\n\r\n"
    b_str_data = str_data.encode()
    jeblur
    jeblur
    OP
    Apr 9, 2020
    5
    @gimp 感谢,所以这个是上面方法的完整做法?
    gimp
    gimp
    Apr 9, 2020
    6
    如果需要动态拼接内容,就用 encode() 编码后发送,固定值可以用 b"" 来标注内容类型。
    leavic
    leavic
    Apr 9, 2020
    7
    我不知道我理解对不对
    1 、用引号圈起来的默认是 string
    2 、跟机器交互一般都用过 bytes 数据,不是 string
    3 、string encode 成 bytes 给机器用,bytes decode 成 string 给人读。
    linvaux
    linvaux
    Apr 9, 2020
    8
    貌似有个工具 2to3 可以转
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1484 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 10:43 · PVG 18:43 · LAX 02:43 · JFK 05:43
    ♥ Do have faith in what you're doing.