持續更新中...
- 常見異常解決方案
- 1.Base
- 1.1.IndentationError: unexpected indent
- 1.2.TypeError: str returned non-string (type NoneType)
- 1.3.TypeError: 'list' object is not callable
- 1.4.xxx() missing 1 required positional argument: 'self'
- 1.5.'module' object is not callable
- 1.6.AttributeError:
__enter__
- 1.7.'gbk' codec can't decode byte 0xff in position 3451: illegal multibyte sequence
- 1.8.RuntimeError: Queue objects should only be shared between processes through inheritance
- 1.9.OSError: [Errno 98] Address already in use
- 1.10.Win下端口占用問題:OSError: [WinError 10013] 以一種訪問權限不允許的方式做了一個訪問套接字的嘗試
- 1.11.Win下Python包不能安裝的說明
- 網站
- PYPI
- 2.Web
- 3.Spider
- Python常見異常彙總
- 1.Base
常見異常解決方案
1.Base
Python3.7環境相關:https://www.cnblogs.com/dotnetcrazy/p/9095793.html
1.1.IndentationError: unexpected indent
===>檢查一下縮進,可以借用yapf或者pycodestyle來幫忙
可以參考這篇文章的末尾:https://www.cnblogs.com/dotnetcrazy/p/9095793.html
1.2.TypeError: str returned non-string (type NoneType)
==> def str(self) 裏面沒有return返回值
1.3.TypeError: 'list' object is not callable
==>'list'對象不可調用,一般都是用戶自定變量和list重名了
原因:
1.4.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()
1.5.'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,那問題就來了~所以,就算隨手測試也是要命名規範的-_-#
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()
即可
https://www.cnblogs.com/dotnetcrazy/p/9426279.html#擴展補充
1.9.OSError: [Errno 98] Address already in use
具體可以查看此文章:https://www.cnblogs.com/dotnetcrazy/p/10003762.html
1.10.Win下端口占用問題:OSError: [WinError 10013] 以一種訪問權限不允許的方式做了一個訪問套接字的嘗試
https://www.cnblogs.com/dotnetcrazy/p/10093178.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.
解決:https://www.cnblogs.com/dotnetcrazy/p/10779304.html
3.Spider
3.1.通用
'gbk' codec can't encode character '\xa0' in position 34: illegal multibyte sequence
https://www.cnblogs.com/dotnetcrazy/p/10803209.html
Python常見異常彙總
有些異常官方沒有寫進去,我補了一些常用的異常:https://docs.python.org/3/library/exceptions.html
BaseException
SystemExit
:sys.exit()
引發的異常(目的:讓Python解釋器退出)KeyboardInterrupt
:用戶Ctrl+C終止程序引發的異常GeneratorExit
:生成器或者協程關閉的時候產生的異常(特別注意)Exception
:所有內置異常(非系統退出)或者用戶定義異常的基類asyncio.Error
asyncio.CancelledError
asyncio.TimeoutError
:和Exception.OSError.TimeoutError
區分開asyncio.InvalidStateError
:Task/Future
內部狀態無效引發
asyncio.LimitOverrunError
:超出緩衝區引發的異常StopIteration
:next()、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