python2与python3 socket sendto 参数类型不同问题

本文介绍在Python3中解决UDP发包时遇到的TypeError问题,详细解释了Python2与Python3在处理字符串和字节类型上的差异,并提供了解决方案。

一段发包代码,在python2.x下没问题:

udp_sock_fd.sendto(msg, (target_ip, target_port))

但在python3.x下出现错误,提示:

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

python3.x和python2.x对于参数类型定义不同,

python3.x使用bytes, python2使用str类型,

bytes和str可以通过encode(), decode()相互转换,
str--->bytes:encode(),将str转换为bytes。
bytes--->str:decode(),把bytes变为str。

python3.x这么写就对了:

udp_sock_fd.sendto(msg.encode(), (target_ip, target_port))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值