1. 程式人生 > >常見的python報錯及解決方案

常見的python報錯及解決方案

1
NameError變數名錯誤

報錯:

>>> print a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

解決方案:

先要給a賦值。才能使用它。在實際編寫程式碼過程中,報NameError錯誤時,檢視該變數是否賦值,或者是否有大小寫不一致錯誤,或者說不小心將變數名寫錯了。

注:在Python中,無需顯示變數宣告語句,變數在第一次被賦值時自動宣告。

>>> a=1
>>> print a
1

2
IndentationError程式碼縮排錯誤
程式碼:

a=1b=2
if a<b:
print a

報錯:

IndentationError: expected an indented block

原因:

縮排有誤,python的縮排非常嚴格,行首多個空格,少個空格都會報錯。這是新手常犯的一個錯誤,由於不熟悉python編碼規則。像def,class,if,for,while等程式碼塊都需要縮排。

縮排為四個空格寬度,需要說明一點,不同的文字編輯器中製表符(tab鍵)代表的空格寬度不一,如果程式碼需要跨平臺或跨編輯器讀寫,建議不要使用製表符。

解決方案:

a=1b=2
if a<b:
    print a

3
AttributeError物件屬性錯誤

報錯:

>>> import sys

>>> sys.Path
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'Path'

原因:

sys模組沒有Path屬性。

解決方案:

python對大小寫敏感,Path和path代表不同的變數。將Path改為path即可。

>>> sys.path
['',  '/usr/lib/python2.6/site-packages']

python知識拓展:

使用dir函式檢視某個模組的屬性

>>> dir(sys)
['__displayhook__', '__doc__', '__egginsert', '__excepthook__', '__name__', '__package__', '__plen', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'hexversion', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'py3kwarning', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions']

4
TypeError型別錯誤

1
入參型別錯誤

程式碼:

t=('a','b','c')
for i in range(t):
    print a[i]

報錯:

TypeError: range() integer end argument expected, got tuple.

原因:

range()函式期望的入參是整型(integer),但卻給的入參為元組(tuple)

解決方案:

將入參元組t改為元組個數整型len(t)

將range(t)改為range(len(t))

2
入參個數錯誤
關於元組作為入參
程式碼:

報錯:

Traceback (most recent call last):

  File "D:\system files\workspace\selenium\autotestcombat\test_4_7_1_webdriverwait.py", line 18, in <module>
    element=WebDriverWait(driver,5,0.5).until(EC.visibility_of_element_located(*loc))
TypeError: __init__() takes exactly 2 arguments (3 given)

原因:
類的函式__init__()需要兩個引數,但實際上給了三個。
EC.visibility_of_element_located類的入參應該是兩個入參: self和元組。但卻給了三個引數 self和loc中的兩個元素作為入參。
解決方案:
這裡要將EC.visibility_of_element_located(loc)改為EC.visibility_of_element_located(loc),入參為元組,而不是元組裡邊的兩個值。
python知識拓展:
關於入參
的用法
以元組作為函式入參,如果元組前加
號,說明傳遞的入參為元組中的各個元素。如果元組前沒有加*號,說明傳遞的入參為元組本身。
舉例說明:

loc =(By.NAME,'email')
element1=WebDriverWait(driver,5,0.5).until(EC.visibility_of_element_located(loc)) #只要一個引數(不考慮self情況下),元組loc,即:(By.NAME,'email')。 直接傳loc。
element2=driver.find_element(*loc)#需要兩個引數,元組loc的元素,即:By.NAME,'email'。直接傳*loc

3
其他
報錯:

>>> import os

>>> os.listdir()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: listdir() takes exactly 1 argument (0 given)

原因:

listdir()函式需要一個入參,但是隻給了0個入參。

解決方案:

加一個入參

>>> os.listdir('/home/autotest')
['hello.py', 'email126pro']

python知識拓展:

如何檢視某個函式的使用,可以使用help檢視。

>>> help(os.listdir)
Help on built-in function listdir in module posix:

listdir(...)
listdir(path) -> list_of_strings

Return a list containing the names of the entries in the directory.

path: path of directory to list

說明:os.listdir()函式需要一個path路徑入參,函式結果返回值是由字串組成的列表。

4
非函式卻以函式來呼叫
報錯:

>>> t=('a','b','c')
>>> t()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

原因:

t為元組,元組不能被呼叫,不能加()。初學者編寫程式碼時,偶爾粗心會將變數當做方法來呼叫(不小心加了括號)。所以要認真檢查下是否變數加了括號,或者方法漏加了括號。

解決方案:

將括號去除。

>>> t
('a', 'b', 'c')

5
IOError輸入輸出錯誤
1
檔案不存在報錯
報錯:

>>> f=open("Hello.py")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'Hello.py'

原因:

open()函式沒有指明mode,預設為只讀方式,如果該目錄下沒有Hello.py的檔案,則會報錯,可檢視是否拼寫有錯誤,或者是否大小寫錯誤,或者根本不存在這個檔案。

解決方案:

該目錄下有hello.py檔案,開啟該檔案即可。

>>> f=open("hello.py")

python知識拓展:

如何檢視python直譯器當前路徑:

>>> import os

>>> os.getcwd()

'/home/autotest'

檢視python直譯器當前路徑下有哪些檔案:

>>> os.listdir('/home/autotest')
['hello.py', 'email126pro']

2
因檔案許可權問題報錯
報錯:

>>> f=open("hello.py")

>>> f.write("test")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: File not open for writing

原因:

open(“hello.py”)如果入參沒有加讀寫模式引數mode,說明預設開啟檔案的方式為只讀方式,而此時又要寫入字元,所以許可權受限,才會報錯。

解決方案:

更改模式

>>> f=open("hello.py",'w+')

>>> f.write("test")

6
KeyError字典鍵值錯誤
報錯:

常見報錯有,測試一介面,介面返回資料一般是json格式,而測試該介面校驗某個值是否正確,如果key拼寫錯了,就會報KeyError。簡單舉例如下:

>>> d={'a':1,'b':2,'c':3}
>>> print d['a']
1
>>> print d['f']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'f'

解決方案:

訪問d中有的鍵值,如a,b或c。

作者:煜妃
源自:https://www.cnblogs.com/yufeihlf/p/6068589.html#test0
宣告:文章著作權歸作者所有,如有侵權,請聯絡博主刪除