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
771456556
V2EX  ›  Python

关于 python2 和 python3 的 string 和 bytes 的问题

  •  
  •   771456556 · 2017-03-12 14:14:21 +08:00 · 2710 次点击
    这是一个创建于 2615 天前的主题,其中的信息可能已经有所发展或是发生改变。

    学校用的是 Dr.com 的校园网客户端,有个大神用 python 写出了客户端,然后我一直在使用,最近转到了 python3 ,然后就想把那个客户端改写成 python3 的版本,然后在 string 和 bytes 这里费解了很久。

    python2.7 版本的代码

    t = struct.pack("<H", int(ran)%(0xFFFF)) #这里的 t 的 type 为 bytes

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    s.sendto("\x01\x02"+t+"\x09"+"\x00"*15, (svr, 61440))

    以上代码在 python3 上面运行时会报错 TypeError: Can't convert 'bytes' object to str implicitly

    然后我把那段代码改写成 s.sendto('\x01\x02'.encode('utf-8')+t+"\x09".encode('utf-8')+"\x00".encode('utf-8')*15, (svr, 61440))不提示报错了,可是无法登陆。

    然后我用python2.7 print 了一下s.sendto的值,发现是20,然后python3 print了一下也是20,可是python3就是登陆失败,请问是我改写的代码有问题吗?

    7 条回复    2017-03-13 07:48:53 +08:00
    a87150
        1
    a87150  
       2017-03-12 14:48:34 +08:00   ❤️ 1
    只要加个 b 来表示是二进制就行了吧
    imn1
        2
    imn1  
       2017-03-12 15:00:00 +08:00   ❤️ 1
    这样写也可以,更简单的写成 b'\x01...'形式就行了
    不能登录是其他原因,检查一下 2/3 哪些语句变了
    771456556
        3
    771456556  
    OP
       2017-03-12 15:30:50 +08:00
    @a87150 对, 但是我之前加了 b 还是不行,我以为是 python3 改了呢,是我错了。。。
    771456556
        4
    771456556  
    OP
       2017-03-12 15:31:16 +08:00
    @imn1 好的,我再查查去,看来应该是别的地方有问题。
    flniu
        5
    flniu  
       2017-03-12 16:32:45 +08:00   ❤️ 1
    如果没有第三方包,可以试试 Python 自带 2to3 命令。
    771456556
        6
    771456556  
    OP
       2017-03-12 17:23:40 +08:00 via Android
    @flniu 已经试过了, 2to3 还没我手动好使呢…我改的这段代码, 2to3 根本就识别不出来
    771456556
        7
    771456556  
    OP
       2017-03-13 07:48:53 +08:00 via Android
    查明了原因了,是因为 python3 里面 socks 需要用 bytes ,所以需要把所有关于 socks 的数据都转换成 bytes,在 github 上联系到了作者,他们打算有时间就修改一下。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1594 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 17:02 · PVG 01:02 · LAX 10:02 · JFK 13:02
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.