Python3调试过程中的常见异常(最近更新:2018-11-26)

持续更新中...

Python3.7环境相关:https://www.cnblogs.com/dotnetcrazy/p/9095793.html

IndentationError: unexpected indent

===>检查一下缩进,可以借用yapf或者pycodestyle来帮忙

可以参考这篇文章的末尾:https://www.cnblogs.com/dotnetcrazy/p/9095793.html


TypeError: str returned non-string (type NoneType)

==> def str(self) 里面没有return返回值


TypeError: 'list' object is not callable

==>'list'对象不可调用,一般都是用户自定变量和list重名了

原因:


xxx() missing 1 required positional argument: 'self'

==>装饰实例方法的时候容易出现莫名其妙的错误,所以一般加上get方法,来个案例:

import types
from functools import wraps

class Log(object):
    def __init__(self, func):
        wraps(func)(self)  # @wraps(func) 访问不到,所以用这种方式
        self.__func = func

    def __call__(self, *args, **kvs):
        print("%s log_info..." % self.__func.__name__)
        return self.__func(*args, **kvs)

    # 装饰实例方法的时候容易出现莫名其妙的错误,所以一般加上get方法
    # eg:show() missing 1 required positional argument: 'self'
    def __get__(self, instance, cls):
        if instance is None:
            return self
        else:
            return types.MethodType(self, instance)

class LoginComponent(object):
    def __init__(self, name):
        self.__name = name

    @Log
    def show(self):
        """实例方法"""
        print("欢迎你:%s" % self.__name)

    @classmethod
    @Log  # 写在下面("从下往上装,从上往下拆")
    def login_in(cls):
        """类方法"""
        print("登录ing")

    @staticmethod
    @Log
    def show_news():
        """静态方法"""
        print("今天的新闻是...")

def main():
    LoginComponent.login_in()
    LoginComponent.show_news()
    login = LoginComponent("小明")
    login.show()

if __name__ == '__main__':
    main()

'module' object is not callable

eg:TypeError: 'module' object is not callable

原因:命令不规范,或者你导入的模块当做类来使用了

比如今天写demo的时候,随手创建了个文件名:mmap.py

import mmap

fd = os.open("mmap_file", os.O_RDWR)  # 读+写
m = mmap.mmap(fd, 0)  # 创建映射

导入的模块也是mmap,那问题就来了~所以,就算随手测试也是要命名规范的-_-#


AttributeError: __enter__

一般都是上下文管理器with xxx as x:的问题,看看是否不能托管的进行了托管,或者自定义上下文管理器__enter__方法有问题


'gbk' codec can't decode byte 0xff in position 3451: illegal multibyte sequence

一般都是编码问题,Linux一切正常,win下面出现了糟心事

解决:

指定编码:头文件包含# _*_ coding:utf-8 _*_ and 指定编码格式 encoding="utf-8"

还出现错误就忽略吧:errors='ignore' eg:with open("bai.csv","r",errors='ignore') as f:


RuntimeError: Queue objects should only be shared between processes through inheritance

队列对象只能通过继承进程之间共享,因为用到了Pool,multiprocessing.Queue()会有点问题,换为multiprocessing.Manager().Queue()即可

https://www.cnblogs.com/dotnetcrazy/p/9426279.html#扩展补充


OSError: [Errno 98] Address already in use

具体可以查看此文章:https://www.cnblogs.com/dotnetcrazy/p/10003762.html

Socket版

端口被占的处理:tcp_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)

一般情况图示:

解决后图示:

完整示例代码:

from socket import socket, SOL_SOCKET, SO_REUSEADDR

def main():
    with socket() as tcp_socket:
        # 防止端口占用
        tcp_socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
        # 绑定端口
        tcp_socket.bind(('', 8080))
        # 监听
        tcp_socket.listen()
        # 等待
        client_socket, address = tcp_socket.accept()
        # 收发消息
        with client_socket:
            print(f"[来自{address}的消息:\n")
            msg = client_socket.recv(2048)
            if msg:
                print(msg.decode("utf-8"))
            client_socket.send(
                """HTTP/1.1 200 ok\r\nContent-Type: text/html;charset=utf-8\r\n\r\n<h1>哈哈哈</h1>"""
                .encode("utf-8"))

if __name__ == "__main__":
    main()

SocketServer版

from socket import SOL_SOCKET, SO_REUSEADDR
from socketserver import ThreadingTCPServer, BaseRequestHandler

class MyHandler(BaseRequestHandler):
    def handle(self):
        print(f"[来自{self.client_address}的消息:]")
        data = self.request.recv(2048)
        print(data)
        self.request.send(
            "HTTP/1.1 200 ok\r\nContent-Type: text/html;charset=utf-8\r\n\r\n<h1>小明,晚上吃鱼汤吗?</h1>"
            .encode("utf-8"))

def main():
    # bind_and_activate=False 手动绑定和激活
    with ThreadingTCPServer(('', 8080), MyHandler, False) as server:
        # 防止端口占用
        server.socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
        server.server_bind()  # 自己绑定
        server.server_activate()  # 自己激活
        server.serve_forever()

if __name__ == "__main__":
    main()

解决前:
1.server_port_error.gif

解决后:
1.server_port.gif

这个就涉及到TCP4次握手相关的内容了,如果不是长连接,你先断开客户端,再断开服务端就不会遇到这个问题了,具体问题下次继续探讨~


Win下端口占用问题:OSError: [WinError 10013] 以一种访问权限不允许的方式做了一个访问套接字的尝试

https://www.cnblogs.com/dotnetcrazy/p/10093178.html

todo

posted @ 2018-06-17 09:21 鲲逸鹏 阅读(...) 评论(...) 编辑 收藏