【问题标题】:can't concatenate strings in Python-3无法在 Python-3 中连接字符串
【发布时间】:2013-04-25 14:09:18
【问题描述】:

在 Python-3 中运行此脚本时:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import socket
import random
import os
import threading
import sys

class bot(threading.Thread):
   def __init__( self, net, port, user, nick, start_chan ): 
       self.id= random.randint(0,1000)
       self.irc = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
       self.irc_connect ( net, port )
       self.irc_set_user( user,nick )
       self.irc_join( start_chan )
       self.finnish=False
       threading.Thread.__init__(self)

   def run( self ):
       while not self.finnish:
           serv_data_rec = self.irc.recv ( 4096 )
           if serv_data_rec.find ( "PING" ) != -1:
               self.irc.send( "PONG"+ serv_data_rec.split() [ 1 ] + "\r\n" )

           elif serv_data_rec.find("PRIVMSG")!= -1:
               line = serv_data_rec.split( "!" ) [ 0 ] + " :" + serv_data_rec.split( ":" ) [ 2 ]

               self.irc_log( line )
               self.irc_message( line )

   def stop( self ):
       self.finnish = True
       self.irc_quit()

   def irc_connect( self, net, port ):
       self.net = net
       self.port = port
       self.irc.connect ( ( net, port ) )

   def irc_set_user( self, user, nick ):
       self.user = user
       self.nick = nick
       self.irc.send( "NICK " + nick + "\r\n" )
       self.irc.send( "USER " + user + "\r\n" )

   def irc_join( self, chan ):
       self.chan = chan
       self.irc.send( "JOIN " + chan + "\r\n" )

   def irc_message( self, msg ):
       self.irc.send( "PRIVMSG " + self.chan+" " + msg + " \r\n" )

   def irc_message_nick( self, msg , nick):
       self.irc.send( "PRIVMSG " + self.chan+" " + nick + " " + msg + " \r\n" )

   def irc_ping( self ):
       self.irc.send("PING :" + self.net)

   def irc_log( self, line ):
       if not os.path.exists("./logs"):
           os.makedirs("./logs")
       f = open("./logs/" + self.net + self.chan + "#" + "% s" %self.id,'a')
       try:
           f.write( line )
       finally:
           f.close()

   def irc_quit( self ):
       self.irc.send( "QUIT\r\n" )

   def irc_quit_msg(self, msg):
       self.irc.send( "QUIT :" + msg + "\r\n" )

def main():
    bot_main= bot( "irc.freenode.net",6667,"botty botty botty :Python IRC","hello_nick","#martin3333" )
    bot_main.start()
    while 1:
        inp = raw_input()
        if inp =="!QUIT": 
            bot_main.stop()
            break
    sys.exit(0)

if __name__ == '__main__': main()

我得到以下回溯:

File "./hatebozzer.py", line 84, in <module>
    if __name__ == '__main__': main()
File "./hatebozzer.py", line 75, in main
    bot_main= bot( "irc.freenode.net",6667,"botty botty botty :Python IRC","hello_nick","#martin3333" )
File "./hatebozzer.py", line 14, in __init__
    self.irc_set_user( user,nick )
File "./hatebozzer.py", line 43, in irc_set_user
    self.irc.send( "NICK " + nick + "\r\n" )
TypeError: 'str' does not support the buffer interface

我知道字符串在 Python 3 中的处理方式完全不同,但我并不想转换字符串或做任何奇特的事情。 我只是想连接它们,所以我在这里做错了什么?

【问题讨论】:

  • 不是串联,.send()接收你希望它接收的字符串。它只是不满意得到一个字符串。
  • @delnan 但是为什么它在 Python-2.x 中工作呢?
  • 参见this answer - Python 3 和 Python 2 对字符串的处理方式不同。

标签: string python-3.x


【解决方案1】:

send 想要一个 bytes 序列作为它的参数。

在 Python2 中,"NICK " + nick + "\r\n" 是一个字节序列。 但在 Python3 中,它是 str,在 Python2 中会被称为 unicode。在 Python3 中,这不是字节序列。

在 Python3 中,要将 str 转换为字节序列,请应用编码:

("NICK " + nick + "\r\n").encode('utf-8')

或(要遵循最佳做法,请使用 format 而不是 +):

"NICK {n}\r\n".format(n=nick).encode('utf-8')

【讨论】:

  • TypeError: Can't convert 'bytes' object to str implicitly, but we want to convert str to bytes or not we?
  • 抱歉,我忘记了 str 周围的括号。
  • 谢谢,但我可能不会喜欢 Python 3 ... ^^
【解决方案2】:

您链接到的代码兼容 Python 3。

您正在尝试将 Unicode 字符串发送到套接字,而该套接字需要 bytes。该代码还使用了raw_input(),在 Python 3 中已重命名为 input

改用 Python 2 运行该代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-02
    • 2019-03-22
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多