开发者

Python Error: Argument 1 must be buffer or bytes not str

The program is simple, it is meant to connect to an IRC room. The pr开发者_如何学Coblem is that when I try to connect my bot to it, it gives me the error in the title. I am not sure what they want instead of a string. I am not sure what buffer or bytes refers to. Others have gotten this script to work, but its not working for me. Note: This is not a malicous irc bot or whatever. This is just an exercise with some basic networking.

import socket

network = 'irc.rizon.net'
port = 6667
irc = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
irc.connect((network,port))

irc.send("NICK PyBot\r\n")
irc.send("USER Pybot Pybot Pybot : Python IRC\r\n")
irc.send("JOIN #pychat\r\n")
irc.send("PART #pychat\r\n")
irc.send("QUITE\r\n")
irc.close()


You're using Python 3, while the script was written for Python 2. The quick fix is to make the string literals bytes literals by adding a b before them:

irc.sendall(b"NICK PyBot\r\n")
irc.sendall(b"USER Pybot Pybot Pybot : Python IRC\r\n")
irc.sendall(b"JOIN #pychat\r\n")
irc.sendall(b"PART #pychat\r\n")
irc.sendall(b"QUITE\r\n")

In Python 3, a str is a sequence of characters. A bytes is a sequence of, well, bytes.

EDIT: I think Jean is referring to the fact that socket.send is not guaranteed to send all the bytes. The quick fix for that is to use sendall.


Assuming you're using Python 3.x:

You have to send bytes over a socket, not str.

irc.send(b"NICK PyBot\r\n")

For a good explanation of bytes vs. str, see the Strings chapter of Dive Into Python 3.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜