Python3开发过程常见的异常(最近更新:2019-04-26)

持续更新中...html

常见异常解决方案

1.Base

Python3.7环境相关:http://www.javashuo.com/article/p-tvzhtwbx-bq.htmlpython

1.1.IndentationError: unexpected indent

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

能够参考这篇文章的末尾:http://www.javashuo.com/article/p-tvzhtwbx-bq.htmlmysql


1.2.TypeError: str returned non-string (type NoneType)

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


1.3.TypeError: 'list' object is not callable

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

缘由:
django


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

==>装饰实例方法的时候容易出现莫名其妙的错误,因此通常加上get方法,来个案例:async

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()

1.5.'module' object is not callable

eg:TypeError: 'module' object is not callable

缘由:命令不规范,或者你导入的模块当作类来使用了ide

好比今天写demo的时候,随手建立了个文件名:mmap.py函数

import mmap

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

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


1.6.AttributeError: __enter__

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


1.7.'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:


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

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

http://www.javashuo.com/article/p-hufkkonm-d.html


1.9.OSError: [Errno 98] Address already in use

具体能够查看此文章:http://www.javashuo.com/article/p-phkqmcgd-v.html

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

http://www.javashuo.com/article/p-qdnbxexf-bx.html

1.11.Win下Python包不能安装的说明

网站

Win下Py包安装出错就去这个网站下对应包:https://www.lfd.uci.edu/~gohlke/pythonlibs/

而后 pip install xxx

PYPI

去PyPI搜索包,而后左侧菜单栏有下载连接

以后pip install xxx 便可


2.Web

2.1.Django

1.django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.

解决:http://www.javashuo.com/article/p-auijtlyq-ck.html

3.Spider

3.1.通用

'gbk' codec can't encode character '\xa0' in position 34: illegal multibyte sequence

http://www.javashuo.com/article/p-acwbbimg-cv.html

Python常见异常汇总

有些异常官方没有写进去,我补了一些经常使用的异常:https://docs.python.org/3/library/exceptions.html

BaseException

  • SystemExitsys.exit()引起的异常(目的:让Python解释器退出)
  • KeyboardInterrupt:用户Ctrl+C终止程序引起的异常
  • GeneratorExit:生成器或者协程关闭的时候产生的异常(特别注意
  • Exception:全部内置异常(非系统退出)或者用户定义异常的基类
    • asyncio.Error
      • asyncio.CancelledError
      • asyncio.TimeoutError:和Exception.OSError.TimeoutError区分开
      • asyncio.InvalidStateErrorTask/Future内部状态无效引起
    • asyncio.LimitOverrunError:超出缓冲区引起的异常
    • StopIterationnext()、send()引起的异常:
      • https://www.cnblogs.com/dotnetcrazy/p/9278573.html#6.Python迭代器
    • StopAsyncIteration__anext__()引起的异常
    • ArithmeticError
      • FloatingPointError
      • OverflowError
      • ZeroDivisionError
    • AssertionError:当断言assert语句失败时引起
    • AttributeError:当属性引用或赋值失败时引起
    • BufferError
    • EOFError
      • asyncio.IncompleteReadError:读取操做未完成引起的错误
    • ImportError
      • ModuleNotFoundError
    • LookupError
      • IndexError
      • KeyError
    • MemoryError
    • NameError
      • UnboundLocalError
    • OSError:当系统函数返回与系统相关的错误时引起
      • BlockingIOError
      • ChildProcessError
      • ConnectionError
        • BrokenPipeError
        • ConnectionAbortedError
        • ConnectionRefusedError
        • ConnectionResetError
      • FileExistsError
      • FileNotFoundError
      • InterruptedError
      • IsADirectoryError
      • NotADirectoryError
      • PermissionError
      • ProcessLookupError
      • TimeoutError:系统函数执行超时时触发
    • ReferenceError:引用错误(对象被资源回收或者删除了)
    • RuntimeError:出错了,可是检测不到错误类别时触发
      • NotImplementedError:为实现报错(好比调用了某个不存在的子类方法)
      • RecursionError:递归程度太深引起的异常
      • asyncio.SendfileNotAvailableError:系统调用不适用于给定的套接字或文件类型
    • SyntaxError:语法错误时引起(粘贴代码常常遇到
      • IndentationError:缩进有问题
      • TabError:当缩进包含不一致的制表符和空格使用时引起
    • SystemError
    • TypeError:类型错误
    • ValueError
      • UnicodeError
      • UnicodeDecodeError
      • UnicodeEncodeError
      • UnicodeTranslateError
    • Warning
    • DeprecationWarning
    • PendingDeprecationWarning
    • RuntimeWarning
    • SyntaxWarning
    • UserWarning
    • FutureWarning
    • ImportWarning
    • UnicodeWarning
    • BytesWarning
    • ResourceWarning
相关文章
相关标签/搜索