码迷,mamicode.com
首页 > 编程语言 > 详细

python3学习问题汇总

时间:2016-07-31 11:33:42      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:

1、python2脚本转python3报类型错误

TypeError: ‘str’ does not support the buffer interface

原因:Python3x的string类型与Python2x的类型不相同,在Python3x中需要将str编码,如:

套接字的成员函数send

socket.send(bytes[, flags]) 形参为字节类型

socket.recv(bufsize[, flags]) Receive datafrom the socket. The return value is abytes object representing the data received.

 1 def Deal(sock, user):
 2     while True:
 3         data = sock.recv(BUFSIZ).decode() #接收用户的数据
 4 
 5         # print(data)
 6         print(re.match([to:.+], data))
 7         if data == quit: #用户退出
 8             del clients[user]
 9             sock.send(data).encode().decode()
10             sock.close()
11             print(%s logout %user)
12             break
13         elif re.match(to:.+, data) is not None: #选择通信对象
14             data = data[3:]
15             print(data)
16             if data in clients:
17                 chatwith[sock] = clients[data]
18                 chatwith[clients[data]] = sock
19             else:
20                 sock.send(the user %s is not exist %data.encode())
21         else:
22             if sock in chatwith: #进行通信
23                 chatwith[sock].send(("[%s] %s: %s" %(ctime(), user, data)).encode())
24             else:
25                 sock.send(Please input the user who you want to chat with.encode())

2、python3中使用has_key报错

原因:python3中已经  包含此 项

解决方法:

用 k in dict 的方式代替

 1 while True:
 2     print(waiting for connection...)
 3     tcpCliSock, addr = tcpSerSock.accept()
 4     print(tcpCliSock,addr)
 5     print(...connected from:,addr)
 6     username = tcpCliSock.recv(BUFSIZ).decode() #接收用户名
 7     print(The username is:,username)
 8     if username in clients: #查找用户名
 9         tcpCliSock.send("Reuse").encode() #用户名已存在
10         tcpCliSock.close()
11     else:
12         tcpCliSock.send("Welcome!".encode()) #登入成功
13         clients[username] = tcpCliSock
14         chat = threading.Thread(target = Deal, args = (tcpCliSock,username)) #创建新线程进行处理
15         chat.start() #启动线程

 

python3学习问题汇总

标签:

原文地址:http://www.cnblogs.com/xiaoyaowuming/p/5722449.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!