python遇見的錯誤提示

第一種:TypeError: an integer is required (got type str)

def send_msg(udp_scoket):
    '''發送信息'''
    dest_ip = input("請輸入對方的IP地址:")
    dest_port = int(input("請輸入對方的端口:"))
    send_data = input("請輸入要發送的內容:")
    udp_scoket.sendto(send_data.encode('utf-8'),(dest_ip,dest_port))

這裏端口號,在scoket中端口號一定要用數字,而在python中經過輸入的字符全都是字符串,需要經過字符串轉碼,把str類型轉成int類型

第二種:UnicodeDecodeError: 'utf-8' codec can't decode byte 0x84 in position 1: invalid start byte

這種是編碼格式錯誤造成的



def rece_msg(udp_scoket):
    recv_data = udp_scoket.recvfrom(1024)
    print(recv_data)
    # print("%s:%s"%(str(recv_data[1]),recv_data[0].decode('utf-8')))

這裏我們先把返回值給打印出來,(b'm;R\xa8V\xdeu5\x8b\xddv\x84V\xde\x8c\x03', ('127.0.0.1', 8877))

我們會看見數據是b'm;R,
備註:現在還沒有找到解決辦法

第三種:ConnectionRefusedError: [Errno 61] Connection refused

這個其實是粗心大意造成的,其實就是socket服務器沒開,拒絕訪問

第四種: t.start()
TypeError: start() missing 1 required positional argument: 'self'

import  threading
import time


class MyThread(threading.Thread):
    def run(self) -> None:
        for i in range(5):
            time.sleep(1)
            msg = "IM " +self.name +"@ "+ str(self)
            print(msg)


'''
注意這個擴展類的方法,只能創建一個線程,並不能創建多個線程

'''



if __name__ == "__main__":
    t = MyThread
    t.start()

請注意觀察倒數第二行,我引用了類對象,但是沒有添加括號,其實這個報錯的就是初始化對象的時候要添加()

第四種:TypeError: a bytes-like object is required, not 'str',這種基本都是編碼格式錯誤造成的,加上編碼格式即可,例如:

new_scoket.send(response.encode('utf-8'))

Traceback (most recent call last):
  File "/Users/wangying/PycharmProjects/Web服務器/05_httpServer_Files.py", line 32, in <module>
    main()
  File "/Users/wangying/PycharmProjects/Web服務器/05_httpServer_Files.py", line 28, in main
    server_client(new_scoket)
  File "/Users/wangying/PycharmProjects/Web服務器/05_httpServer_Files.py", line 13, in server_client
    new_scoket.send(response)
TypeError: a bytes-like object is required, not 'str'

第五種錯誤:TypeError: cannot use a string pattern on a bytes-like object

出錯的主要原因是因爲:

     TypeError: can’t use a string pattern on a bytes-like object.

     html用decode(‘utf-8’)進行解碼,由bytes變成string。

     py3的urlopen返回的不是string是bytes。
解決方法是:把’html’類型調整一下:html.decode(‘utf-8’),給解析的數據,添加個數據類型。

request = new_scoket.recv(1024).decode('utf-8')

第六種錯誤:由 try else except引起的:“SyntaxError: invalid syntax”。這是由於在python3.7中寫的順序錯誤導致的,在3.5中沒事,3.7中需要先寫try,在寫except,再寫else,記得else一定要寫在except的後面


    try:
        print(file_name)
        f = open("/admin"+file_name,'rb')
    except:
        response = 'HTTP/1.1 200 OK\r\n'
        response += '\r\n'
        response += '------------- file  not  found ---------'
        new_scoket.send(response.encode('utf-8'))
    else:
        html_content = f.read()
        f.close()
        # 加\r\n兩個,是由於windows與linuex系統裏面的轉義字符不一樣造成的
        response = 'HTTP/1.1 200 OK\r\n'
        response += '\r\n'
        # 把response header發送回去
        new_scoket.send(response.encode('utf-8'))
        # 把response body發送出去
        new_scoket.send(html_content)


        print("返回的數據", response)
        print("返回的body", html_content)

        print("*" * 100)

第七種錯誤:在引用C語言動態文件時報錯了,報錯的內容
OSError: dlopen(./libdead_loop.so, 6): no suitable image found.  Did find:
  主要是我引用了windows中動態編輯後的文件造成的,其實就是您的python和調用的動態文件之間存在體系結構不匹配。使用file檢查什麼的架構調用的動態文件

解決辦法:

直接使用mac終端再次生成下動態文件

/usr/local/bin/python3.7 /Users/wangying/PycharmProjects/Web服務器/main.py
Traceback (most recent call last):
  File "/Users/wangying/PycharmProjects/Web服務器/main.py", line 7, in <module>
    lib = cdll.LoadLibrary("./libdead_loop.so")
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ctypes/__init__.py", line 442, in LoadLibrary
    return self._dlltype(name)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ctypes/__init__.py", line 364, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: dlopen(./libdead_loop.so, 6): no suitable image found.  Did find:
	./libdead_loop.so: unknown file type, first eight bytes: 0x7F 0x45 0x4C 0x46 0x02 0x01 0x01 0x00
	/Users/wangying/PycharmProjects/Web服務器/libdead_loop.so: unknown file type, first eight bytes: 0x7F 0x45 0x4C 0x46 0x02 0x01 0x01 0x00

第八種錯誤:RecursionError: maximum recursion depth exceeded while calling a Python object

這個錯誤看字面意思就是:遞歸深度超出限制

這有兩種,一種是自己寫的代碼進入死循環了,在反覆遞歸,這時就需要查找原因,找到爲什麼會反覆遞歸,下面的例子中的方法setMoney中self.money = value,就陷入了死循環,會反覆遞歸

class Money(object):
    def __init__(self):
         self.__money = 0
    def getMoney(self):
        return self.__money
    def setMoney(self,value):
        if isinstance(value,int):
            '''
            這裏需要特別注意,當我使用self.money時,其實我調用的是setMoney這個方法,進入了死循環
            '''
            # self.money = value
            #所以我們要使用__money
            self.__money = value
        else:
            print("error:不是整型數字")

    def delMoney(self):
        print("刪除金額")
        del self.__money

    #定義個屬性,當對這個Money設置值時調用setMoney,當獲取值時調用getMoney
    money = property(getMoney,setMoney,delMoney,"商品售價")

a = Money()
print(a.money)
a.money = 100
print(a.money)
del a.money

第二種是我們真的需要深度遞歸,但是遞歸次數超出默認設置,python默認的遞歸深度是很有限的(默認是1000),因此當遞歸深度超過999的樣子,就會引發這樣的一個異常。

解決方法很簡單,在代碼頭部加入:(修改遞歸深度的值,讓它變大大一點)

import sys
sys.setrecursionlimit(1000000)

這樣修改Python最大遞歸爲100萬次,根據個人需求設置次數。

第九種:

問題描述:
InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecureRequestWarning)

這個是在https中禁用證書驗證後提示的

解決:
禁用安全請求警告

  • 如果requests >= 2.16.0
import urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

第十種:

問題藐視:

ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1076)

During handling of the above exception, another exception occurred:

使用https,request要驗證證書,

解決辦法:verify=False

    response = requests.get(url,verify=False)
    print(response)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章