简体   繁体   中英

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 problem 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM