V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2020-04-09 10:58:35 +08:00 · 2857 次点击
    这是一个创建于 1476 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 条回复    2020-04-09 17:56:47 +08:00
    maltoze
        1
    maltoze  
       2020-04-09 11:04:51 +08:00   ❤️ 2
    client.send(b"GET / HTTP/1.1\r\nHost:cn.bing.com\r\n\r\n")
    Mithrandir
        2
    Mithrandir  
       2020-04-09 11:07:36 +08:00
    man 2to3
    mnsw
        3
    mnsw  
       2020-04-09 11:08:40 +08:00
    "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
        4
    gimp  
       2020-04-09 11:09:45 +08:00
    str_data = "GET / HTTP/1.1\r\nHost:cn.bing.com\r\n\r\n"
    b_str_data = str_data.encode()
    jeblur
        5
    jeblur  
    OP
       2020-04-09 11:27:40 +08:00
    @gimp 感谢,所以这个是上面方法的完整做法?
    gimp
        6
    gimp  
       2020-04-09 11:36:07 +08:00
    如果需要动态拼接内容,就用 encode() 编码后发送,固定值可以用 b"" 来标注内容类型。
    leavic
        7
    leavic  
       2020-04-09 13:00:45 +08:00
    我不知道我理解对不对
    1 、用引号圈起来的默认是 string
    2 、跟机器交互一般都用过 bytes 数据,不是 string
    3 、string encode 成 bytes 给机器用,bytes decode 成 string 给人读。
    linvaux
        8
    linvaux  
       2020-04-09 17:56:47 +08:00
    貌似有个工具 2to3 可以转
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3535 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 04:52 · PVG 12:52 · LAX 21:52 · JFK 00:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.