zoukankan      html  css  js  c++  java
  • python3学习问题汇总

    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() #启动线程
  • 相关阅读:
    关于对话框创建与销毁的虚函数用法
    控件属性设置注意事项
    删除非空文件夹下所有内容方法
    CString类使用技巧
    视图间通信方法
    CTreeCtrl控件使用技巧
    MFC MDI 遍历打开的所有文档
    将datagrid的数据源到出导excel
    ASP.NET 給一組控件賦值 範例.
    ASP.NET Resouce Kit
  • 原文地址:https://www.cnblogs.com/xiaoyaowuming/p/5722449.html
Copyright © 2011-2022 走看看