Trong lập trình máy tính và phát triển phần mềm, gỡ lỗi là quá trình tìm và giải quyết các lỗi [lỗi hoặc sự cố ngăn cản hoạt động chính xác] trong các chương trình, phần mềm hoặc hệ thống máy tính.
Tăng ngoại lệ
Các ngoại lệ được nêu ra với một tuyên bố tăng. Trong mã, một câu lệnh nâng cao bao gồm những điều sau đây
- Từ khóa
raise
- Một cuộc gọi đến chức năng
0>>> def box_print[symbol, width, height]: ... if len[symbol] != 1: ... raise Exception['Symbol must be a single character string.'] ... if width > for sym, w, h in [['*', 4, 4], ['O', 20, 5], ['x', 1, 3], ['ZZ', 3, 3]]: ... try: ... box_print[sym, w, h] ... except Exception as err: ... print['An exception happened: ' + str[err]] ... # **** # * * # * * # **** # OOOOOOOOOOOOOOOOOOOO # O O # O O # O O # OOOOOOOOOOOOOOOOOOOO # An exception happened: Width must be greater than 2. # An exception happened: Symbol must be a single character string.
- Một chuỗi có thông báo lỗi hữu ích được chuyển đến hàm
0>>> def box_print[symbol, width, height]: ... if len[symbol] != 1: ... raise Exception['Symbol must be a single character string.'] ... if width > for sym, w, h in [['*', 4, 4], ['O', 20, 5], ['x', 1, 3], ['ZZ', 3, 3]]: ... try: ... box_print[sym, w, h] ... except Exception as err: ... print['An exception happened: ' + str[err]] ... # **** # * * # * * # **** # OOOOOOOOOOOOOOOOOOOO # O O # O O # O O # OOOOOOOOOOOOOOOOOOOO # An exception happened: Width must be greater than 2. # An exception happened: Symbol must be a single character string.
>>> raise Exception['This is the error message.']
# Traceback [most recent call last]:
# File "", line 1, in
# raise Exception['This is the error message.']
# Exception: This is the error message.
Thông thường, đó là đoạn mã gọi hàm chứ không phải bản thân hàm biết cách xử lý một ngoại lệ. Vì vậy, bạn sẽ thường thấy một câu lệnh nâng cao bên trong một hàm và các câu lệnh
>>> def box_print[symbol, width, height]:
... if len[symbol] != 1:
... raise Exception['Symbol must be a single character string.']
... if width > for sym, w, h in [['*', 4, 4], ['O', 20, 5], ['x', 1, 3], ['ZZ', 3, 3]]:
... try:
... box_print[sym, w, h]
... except Exception as err:
... print['An exception happened: ' + str[err]]
...
# ****
# * *
# * *
# ****
# OOOOOOOOOOOOOOOOOOOO
# O O
# O O
# O O
# OOOOOOOOOOOOOOOOOOOO
# An exception happened: Width must be greater than 2.
# An exception happened: Symbol must be a single character string.
2 và >>> def box_print[symbol, width, height]:
... if len[symbol] != 1:
... raise Exception['Symbol must be a single character string.']
... if width > for sym, w, h in [['*', 4, 4], ['O', 20, 5], ['x', 1, 3], ['ZZ', 3, 3]]:
... try:
... box_print[sym, w, h]
... except Exception as err:
... print['An exception happened: ' + str[err]]
...
# ****
# * *
# * *
# ****
# OOOOOOOOOOOOOOOOOOOO
# O O
# O O
# O O
# OOOOOOOOOOOOOOOOOOOO
# An exception happened: Width must be greater than 2.
# An exception happened: Symbol must be a single character string.
3 trong mã gọi hàm>>> def box_print[symbol, width, height]:
... if len[symbol] != 1:
... raise Exception['Symbol must be a single character string.']
... if width > for sym, w, h in [['*', 4, 4], ['O', 20, 5], ['x', 1, 3], ['ZZ', 3, 3]]:
... try:
... box_print[sym, w, h]
... except Exception as err:
... print['An exception happened: ' + str[err]]
...
# ****
# * *
# * *
# ****
# OOOOOOOOOOOOOOOOOOOO
# O O
# O O
# O O
# OOOOOOOOOOOOOOOOOOOO
# An exception happened: Width must be greater than 2.
# An exception happened: Symbol must be a single character string.
Đọc thêm về Xử lý ngoại lệ
Lấy Tracback dưới dạng chuỗi
>>> def box_print[symbol, width, height]:
... if len[symbol] != 1:
... raise Exception['Symbol must be a single character string.']
... if width > for sym, w, h in [['*', 4, 4], ['O', 20, 5], ['x', 1, 3], ['ZZ', 3, 3]]:
... try:
... box_print[sym, w, h]
... except Exception as err:
... print['An exception happened: ' + str[err]]
...
# ****
# * *
# * *
# ****
# OOOOOOOOOOOOOOOOOOOO
# O O
# O O
# O O
# OOOOOOOOOOOOOOOOOOOO
# An exception happened: Width must be greater than 2.
# An exception happened: Symbol must be a single character string.
4 được hiển thị bởi Python bất cứ khi nào một ngoại lệ được đưa ra không được xử lý. Nhưng cũng có thể lấy nó dưới dạng một chuỗi bằng cách gọi truy nguyên. định dạng_exc[]. Hàm này rất hữu ích nếu bạn muốn có thông tin từ truy nguyên của một ngoại lệ nhưng cũng muốn có một câu lệnh except để xử lý ngoại lệ một cách duyên dáng. Bạn sẽ cần nhập mô-đun truy nguyên của Python trước khi gọi hàm này>>> import traceback
>>> try:
... raise Exception['This is the error message.']
>>> except:
... with open['errorInfo.txt', 'w'] as error_file:
... error_file.write[traceback.format_exc[]]
... print['The traceback info was written to errorInfo.txt.']
...
# 116
# The traceback info was written to errorInfo.txt.
116 là giá trị trả về từ phương thức
>>> def box_print[symbol, width, height]:
... if len[symbol] != 1:
... raise Exception['Symbol must be a single character string.']
... if width > for sym, w, h in [['*', 4, 4], ['O', 20, 5], ['x', 1, 3], ['ZZ', 3, 3]]:
... try:
... box_print[sym, w, h]
... except Exception as err:
... print['An exception happened: ' + str[err]]
...
# ****
# * *
# * *
# ****
# OOOOOOOOOOOOOOOOOOOO
# O O
# O O
# O O
# OOOOOOOOOOOOOOOOOOOO
# An exception happened: Width must be greater than 2.
# An exception happened: Symbol must be a single character string.
5, vì 116 ký tự được ghi vào tệp. Văn bản >>> def box_print[symbol, width, height]:
... if len[symbol] != 1:
... raise Exception['Symbol must be a single character string.']
... if width > for sym, w, h in [['*', 4, 4], ['O', 20, 5], ['x', 1, 3], ['ZZ', 3, 3]]:
... try:
... box_print[sym, w, h]
... except Exception as err:
... print['An exception happened: ' + str[err]]
...
# ****
# * *
# * *
# ****
# OOOOOOOOOOOOOOOOOOOO
# O O
# O O
# O O
# OOOOOOOOOOOOOOOOOOOO
# An exception happened: Width must be greater than 2.
# An exception happened: Symbol must be a single character string.
4 đã được ghi vào errorInfo. txtTraceback [most recent call last]:
File "", line 2, in
Exception: This is the error message.
khẳng định
Xác nhận là kiểm tra độ chính xác để đảm bảo mã của bạn không làm điều gì đó rõ ràng là sai. Những kiểm tra độ chính xác này được thực hiện bởi các câu lệnh
>>> def box_print[symbol, width, height]:
... if len[symbol] != 1:
... raise Exception['Symbol must be a single character string.']
... if width > for sym, w, h in [['*', 4, 4], ['O', 20, 5], ['x', 1, 3], ['ZZ', 3, 3]]:
... try:
... box_print[sym, w, h]
... except Exception as err:
... print['An exception happened: ' + str[err]]
...
# ****
# * *
# * *
# ****
# OOOOOOOOOOOOOOOOOOOO
# O O
# O O
# O O
# OOOOOOOOOOOOOOOOOOOO
# An exception happened: Width must be greater than 2.
# An exception happened: Symbol must be a single character string.
7. Nếu kiểm tra độ chính xác không thành công, thì một ngoại lệ >>> def box_print[symbol, width, height]:
... if len[symbol] != 1:
... raise Exception['Symbol must be a single character string.']
... if width > for sym, w, h in [['*', 4, 4], ['O', 20, 5], ['x', 1, 3], ['ZZ', 3, 3]]:
... try:
... box_print[sym, w, h]
... except Exception as err:
... print['An exception happened: ' + str[err]]
...
# ****
# * *
# * *
# ****
# OOOOOOOOOOOOOOOOOOOO
# O O
# O O
# O O
# OOOOOOOOOOOOOOOOOOOO
# An exception happened: Width must be greater than 2.
# An exception happened: Symbol must be a single character string.
8 sẽ được đưa ra. Trong mã, một câu lệnh >>> def box_print[symbol, width, height]:
... if len[symbol] != 1:
... raise Exception['Symbol must be a single character string.']
... if width > for sym, w, h in [['*', 4, 4], ['O', 20, 5], ['x', 1, 3], ['ZZ', 3, 3]]:
... try:
... box_print[sym, w, h]
... except Exception as err:
... print['An exception happened: ' + str[err]]
...
# ****
# * *
# * *
# ****
# OOOOOOOOOOOOOOOOOOOO
# O O
# O O
# O O
# OOOOOOOOOOOOOOOOOOOO
# An exception happened: Width must be greater than 2.
# An exception happened: Symbol must be a single character string.
7 bao gồm những điều sau đây- Từ khóa
7>>> def box_print[symbol, width, height]: ... if len[symbol] != 1: ... raise Exception['Symbol must be a single character string.'] ... if width > for sym, w, h in [['*', 4, 4], ['O', 20, 5], ['x', 1, 3], ['ZZ', 3, 3]]: ... try: ... box_print[sym, w, h] ... except Exception as err: ... print['An exception happened: ' + str[err]] ... # **** # * * # * * # **** # OOOOOOOOOOOOOOOOOOOO # O O # O O # O O # OOOOOOOOOOOOOOOOOOOO # An exception happened: Width must be greater than 2. # An exception happened: Symbol must be a single character string.
- Một điều kiện [tức là, một biểu thức đánh giá thành
1 hoặc>>> import traceback >>> try: ... raise Exception['This is the error message.'] >>> except: ... with open['errorInfo.txt', 'w'] as error_file: ... error_file.write[traceback.format_exc[]] ... print['The traceback info was written to errorInfo.txt.'] ... # 116 # The traceback info was written to errorInfo.txt.
2]>>> import traceback >>> try: ... raise Exception['This is the error message.'] >>> except: ... with open['errorInfo.txt', 'w'] as error_file: ... error_file.write[traceback.format_exc[]] ... print['The traceback info was written to errorInfo.txt.'] ... # 116 # The traceback info was written to errorInfo.txt.
- Dấu phẩy
- Một
3 để hiển thị khi điều kiện là>>> import traceback >>> try: ... raise Exception['This is the error message.'] >>> except: ... with open['errorInfo.txt', 'w'] as error_file: ... error_file.write[traceback.format_exc[]] ... print['The traceback info was written to errorInfo.txt.'] ... # 116 # The traceback info was written to errorInfo.txt.
2>>> import traceback >>> try: ... raise Exception['This is the error message.'] >>> except: ... with open['errorInfo.txt', 'w'] as error_file: ... error_file.write[traceback.format_exc[]] ... print['The traceback info was written to errorInfo.txt.'] ... # 116 # The traceback info was written to errorInfo.txt.
>>> pod_bay_door_status = 'open'
>>> assert pod_bay_door_status == 'open', 'The pod bay doors need to be "open".'
>>> pod_bay_door_status = 'I\'m sorry, Dave. I\'m afraid I can\'t do that.'
>>> assert pod_bay_door_status == 'open', 'The pod bay doors need to be "open".'
# Traceback [most recent call last]:
# File "", line 1, in
# assert pod_bay_door_status == 'open', 'The pod bay doors need to be "open".'
# AssertionError: The pod bay doors need to be "open".
Nói một cách dễ hiểu, một câu lệnh khẳng định có nội dung: “Tôi khẳng định rằng điều kiện này đúng và nếu không, có một lỗi ở đâu đó trong chương trình. ” Không giống như các ngoại lệ, mã của bạn không được xử lý các câu lệnh khẳng định bằng thử và ngoại trừ; . Bằng cách thất bại nhanh như vậy, bạn rút ngắn thời gian giữa nguyên nhân ban đầu của lỗi và khi bạn nhận thấy lỗi lần đầu tiên. Điều này sẽ giảm số lượng mã bạn phải kiểm tra trước khi tìm ra mã gây ra lỗi
Vô hiệu hóa xác nhận
Có thể vô hiệu hóa các xác nhận bằng cách chuyển tùy chọn
>>> import traceback
>>> try:
... raise Exception['This is the error message.']
>>> except:
... with open['errorInfo.txt', 'w'] as error_file:
... error_file.write[traceback.format_exc[]]
... print['The traceback info was written to errorInfo.txt.']
...
# 116
# The traceback info was written to errorInfo.txt.
5 khi chạy Pythonghi nhật ký
Để cho phép mô-đun
>>> import traceback
>>> try:
... raise Exception['This is the error message.']
>>> except:
... with open['errorInfo.txt', 'w'] as error_file:
... error_file.write[traceback.format_exc[]]
... print['The traceback info was written to errorInfo.txt.']
...
# 116
# The traceback info was written to errorInfo.txt.
6 hiển thị thông báo bản ghi trên màn hình của bạn khi chương trình của bạn chạy, hãy sao chép phần sau vào đầu chương trình của bạn>>> import logging
>>> logging.basicConfig[level=logging.DEBUG, format=' %[asctime]s - %[levelname]s- %[message]s']
Giả sử bạn đã viết một hàm để tính giai thừa của một số. Trong toán học, giai thừa 4 là 1 × 2 × 3 × 4, hay 24. Giai thừa 7 là 1 × 2 × 3 × 4 × 5 × 6 × 7, hay 5,040. Mở cửa sổ soạn thảo tệp mới và nhập mã sau. Nó có một lỗi trong đó, nhưng bạn cũng sẽ nhập một số thông báo nhật ký để giúp bản thân tìm ra điều gì đang xảy ra. Lưu chương trình dưới dạng factorialLog. py
>>> import logging
>>> logging.basicConfig[level=logging.DEBUG, format=' %[asctime]s - %[levelname]s- %[message]s']
>>> logging.debug['Start of program']
>>> def factorial[n]:
... logging.debug['Start of factorial[%s]' % [n]]
... total = 1
... for i in range[1, n + 1]:
... total *= i
... logging.debug['i is ' + str[i] + ', total is ' + str[total]]
... logging.debug['End of factorial[%s]' % [n]]
... return total
...
>>> print[factorial[5]]
>>> logging.debug['End of program']
# 2015-05-23 16:20:12,664 - DEBUG - Start of program
# 2015-05-23 16:20:12,664 - DEBUG - Start of factorial[5]
# 2015-05-23 16:20:12,665 - DEBUG - i is 0, total is 0
# 2015-05-23 16:20:12,668 - DEBUG - i is 1, total is 0
# 2015-05-23 16:20:12,670 - DEBUG - i is 2, total is 0
# 2015-05-23 16:20:12,673 - DEBUG - i is 3, total is 0
# 2015-05-23 16:20:12,675 - DEBUG - i is 4, total is 0
# 2015-05-23 16:20:12,678 - DEBUG - i is 5, total is 0
# 2015-05-23 16:20:12,680 - DEBUG - End of factorial[5]
# 0
# 2015-05-23 16:20:12,684 - DEBUG - End of program
Cấp độ ghi nhật ký
Các cấp độ ghi nhật ký cung cấp một cách để phân loại các thông điệp tường trình của bạn theo mức độ quan trọng. Có năm cấp độ ghi nhật ký, được mô tả trong Bảng 10-1 từ mức thấp nhất đến mức quan trọng nhất. Tin nhắn có thể được ghi lại ở mỗi cấp bằng chức năng ghi nhật ký khác nhau
LevelLogging FunctionDescription>>> import traceback
>>> try:
... raise Exception['This is the error message.']
>>> except:
... with open['errorInfo.txt', 'w'] as error_file:
... error_file.write[traceback.format_exc[]]
... print['The traceback info was written to errorInfo.txt.']
...
# 116
# The traceback info was written to errorInfo.txt.
7>>> import traceback
>>> try:
... raise Exception['This is the error message.']
>>> except:
... with open['errorInfo.txt', 'w'] as error_file:
... error_file.write[traceback.format_exc[]]
... print['The traceback info was written to errorInfo.txt.']
...
# 116
# The traceback info was written to errorInfo.txt.
8The lowest level. Dùng cho các chi tiết nhỏ. Thông thường, bạn chỉ quan tâm đến những thông báo này khi chẩn đoán sự cố. >>> import traceback
>>> try:
... raise Exception['This is the error message.']
>>> except:
... with open['errorInfo.txt', 'w'] as error_file:
... error_file.write[traceback.format_exc[]]
... print['The traceback info was written to errorInfo.txt.']
...
# 116
# The traceback info was written to errorInfo.txt.
9Traceback [most recent call last]:
File "", line 2, in
Exception: This is the error message.
0Được sử dụng để ghi lại thông tin về các sự kiện chung trong chương trình của bạn hoặc xác nhận rằng mọi thứ đang hoạt động tại thời điểm của chúng trong chương trình. Traceback [most recent call last]:
File "", line 2, in
Exception: This is the error message.
1Traceback [most recent call last]:
File "", line 2, in
Exception: This is the error message.
2Được sử dụng để chỉ ra một vấn đề tiềm ẩn không ngăn cản chương trình hoạt động nhưng có thể làm như vậy trong tương lai. Traceback [most recent call last]:
File "", line 2, in
Exception: This is the error message.
3Traceback [most recent call last]:
File "", line 2, in
Exception: This is the error message.
4Được sử dụng để ghi lại lỗi khiến chương trình không thực hiện được điều gì đó. Traceback [most recent call last]:
File "", line 2, in
Exception: This is the error message.
5Traceback [most recent call last]:
File "", line 2, in
Exception: This is the error message.
6The highest level. Được sử dụng để chỉ ra một lỗi nghiêm trọng đã gây ra hoặc sắp khiến chương trình ngừng chạy hoàn toànVô hiệu hóa ghi nhật ký
Sau khi bạn gỡ lỗi chương trình của mình, có lẽ bạn không muốn tất cả các thông báo bản ghi này làm lộn xộn màn hình. việc ghi nhật ký. hàm disable[] vô hiệu hóa những thứ này để bạn không phải vào chương trình của mình và xóa tất cả các cuộc gọi ghi nhật ký bằng tay
>>> import logging
>>> logging.basicConfig[level=logging.INFO, format=' %[asctime]s -%[levelname]s - %[message]s']
>>> logging.critical['Critical error! Critical error!']
# 2015-05-22 11:10:48,054 - CRITICAL - Critical error! Critical error!
>>> logging.disable[logging.CRITICAL]
>>> logging.critical['Critical error! Critical error!']
>>> logging.error['Error! Error!']
Đăng nhập vào một tập tin
Thay vì hiển thị thông báo tường trình ra màn hình, bạn có thể ghi chúng vào tệp văn bản. Hàm
Traceback [most recent call last]:
File "", line 2, in
Exception: This is the error message.
7 lấy một đối số từ khóa tên tệp, như vậy