Hướng dẫn which method is used to display a warning message in python? - phương pháp nào được sử dụng để hiển thị thông báo cảnh báo trong python?

Mã nguồn: lib/cảnh báo.py Lib/warnings.py


Các thông báo cảnh báo thường được cấp trong các tình huống hữu ích để cảnh báo người dùng một số điều kiện trong một chương trình, trong đó điều kiện đó (thông thường) không đảm bảo tăng ngoại lệ và chấm dứt chương trình. Ví dụ, người ta có thể muốn đưa ra cảnh báo khi một chương trình sử dụng mô -đun lỗi thời.

Các lập trình viên Python đưa ra cảnh báo bằng cách gọi hàm warn() được xác định trong mô -đun này. (C Lập trình viên sử dụng

default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
0; xem Xử lý ngoại lệ để biết chi tiết).Exception Handling for details).

Các thông điệp cảnh báo thường được viết thành

default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
1, nhưng việc xử lý của chúng có thể được thay đổi linh hoạt, từ việc bỏ qua tất cả các cảnh báo để biến chúng thành ngoại lệ. Việc bố trí các cảnh báo có thể thay đổi dựa trên danh mục cảnh báo, văn bản của thông điệp cảnh báo và vị trí nguồn nơi nó được ban hành. Sự lặp lại của một cảnh báo cụ thể cho cùng một vị trí nguồn thường bị triệt tiêu.warning category, the text of the warning message, and the source location where it is issued. Repetitions of a particular warning for the same source location are typically suppressed.

Có hai giai đoạn trong kiểm soát cảnh báo: Thứ nhất, mỗi lần cảnh báo được đưa ra, một quyết định được đưa ra cho dù có nên phát hành tin nhắn hay không; Tiếp theo, nếu một tin nhắn được phát hành, nó được định dạng và in bằng cách sử dụng móc có thể xử lý người dùng.

Việc xác định có đưa ra thông báo cảnh báo được kiểm soát bởi bộ lọc cảnh báo, đây là một chuỗi các quy tắc và hành động phù hợp. Các quy tắc có thể được thêm vào bộ lọc bằng cách gọi

default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
2 và đặt lại về trạng thái mặc định của nó bằng cách gọi
default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
3.warning filter, which is a sequence of matching rules and actions. Rules can be added to the filter by calling
default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
2 and reset to its default state by calling
default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
3.

Việc in các thông điệp cảnh báo được thực hiện bằng cách gọi

default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
4, có thể bị ghi đè; Việc triển khai mặc định của chức năng này định dạng thông báo bằng cách gọi
default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
5, cũng có sẵn để sử dụng bởi các triển khai tùy chỉnh.

Danh mục cảnh báo Jo

Có một số trường hợp ngoại lệ tích hợp đại diện cho các loại cảnh báo. Phân loại này rất hữu ích để có thể lọc các nhóm cảnh báo.

Mặc dù đây là những trường hợp ngoại lệ được tích hợp kỹ thuật, nhưng chúng được ghi nhận ở đây, bởi vì về mặt khái niệm chúng thuộc về cơ chế cảnh báo.built-in exceptions, they are documented here, because conceptually they belong to the warnings mechanism.

Mã người dùng có thể xác định các loại cảnh báo bổ sung bằng cách phân lớp một trong các loại cảnh báo tiêu chuẩn. Một thể loại cảnh báo phải luôn là một lớp con của lớp

default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
6.

Các lớp loại cảnh báo sau đây hiện đang được xác định:

Lớp

Sự mô tả

default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
6

Đây là lớp cơ sở của tất cả các lớp loại cảnh báo. Nó là một lớp con của

default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
8.

default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
9

Danh mục mặc định cho warn().

default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
1

Danh mục cơ sở cho các cảnh báo về các tính năng không dùng nữa khi các cảnh báo đó được dành cho các nhà phát triển Python khác (bị bỏ qua theo mặc định, trừ khi được kích hoạt bởi mã trong

default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
2).

default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
3

Danh mục cơ sở cho các cảnh báo về các tính năng cú pháp đáng ngờ.

default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
4

Danh mục cơ sở cho các cảnh báo về các tính năng thời gian chạy đáng ngờ.

default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
5

Danh mục cơ sở cho các cảnh báo về các tính năng không dùng nữa khi những cảnh báo đó được dành cho người dùng cuối của các ứng dụng được viết bằng Python.

default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
6

Danh mục cơ sở cho các cảnh báo về các tính năng sẽ không được chấp nhận trong tương lai (bị bỏ qua theo mặc định).

default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
7

Danh mục cơ sở cho các cảnh báo được kích hoạt trong quá trình nhập mô -đun (bị bỏ qua theo mặc định).

default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
8

Danh mục cơ sở cho các cảnh báo liên quan đến Unicode.

default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
9

Danh mục cơ sở cho các cảnh báo liên quan đến

import sys

if not sys.warnoptions:
    import warnings
    warnings.simplefilter("ignore")
0 và
import sys

if not sys.warnoptions:
    import warnings
    warnings.simplefilter("ignore")
1.

import sys

if not sys.warnoptions:
    import warnings
    warnings.simplefilter("ignore")
2

Danh mục cơ sở cho các cảnh báo liên quan đến việc sử dụng tài nguyên (bỏ qua theo mặc định).

Đã thay đổi trong phiên bản 3.7: Trước đây

default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
1 và
default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
5 đã được phân biệt dựa trên việc một tính năng có bị xóa hoàn toàn hoặc thay đổi hành vi của nó hay không. Bây giờ họ được phân biệt dựa trên đối tượng dự định của họ và cách họ xử lý bằng các bộ lọc cảnh báo mặc định.Previously
default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
1 and
default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
5 were distinguished based on whether a feature was being removed entirely or changing its behaviour. They are now distinguished based on their intended audience and the way they’re handled by the default warnings filters.

Bộ lọc cảnh báo

Bộ lọc cảnh báo kiểm soát xem các cảnh báo có bị bỏ qua, hiển thị hoặc biến thành lỗi (tăng ngoại lệ).

Về mặt khái niệm, bộ lọc cảnh báo duy trì một danh sách các thông số kỹ thuật của bộ lọc; Bất kỳ cảnh báo cụ thể nào được khớp với từng đặc tả bộ lọc trong danh sách lần lượt cho đến khi tìm thấy một trận đấu; Bộ lọc xác định việc xử lý của trận đấu. Mỗi mục là một bộ phận của biểu mẫu (hành động, tin nhắn, danh mục, mô -đun, lineno), trong đó:

  • Hành động là một trong những chuỗi sau:

    Giá trị

    Bố trí

    import sys
    
    if not sys.warnoptions:
        import warnings
        warnings.simplefilter("ignore")
    
    5

    In lần xuất hiện đầu tiên của các cảnh báo phù hợp cho từng vị trí (mô -đun + số dòng) trong đó cảnh báo được đưa ra

    import sys
    
    if not sys.warnoptions:
        import warnings
        warnings.simplefilter("ignore")
    
    6

    biến các cảnh báo phù hợp thành ngoại lệ

    import sys
    
    if not sys.warnoptions:
        import warnings
        warnings.simplefilter("ignore")
    
    7

    Không bao giờ in cảnh báo phù hợp

    import sys
    
    if not sys.warnoptions:
        import warnings
        warnings.simplefilter("ignore")
    
    8

    Luôn in các cảnh báo phù hợp

    import sys
    
    if not sys.warnoptions:
        import warnings
        warnings.simplefilter("ignore")
    
    9

    In lần xuất hiện đầu tiên của các cảnh báo phù hợp cho mỗi mô -đun nơi cảnh báo được đưa ra (bất kể số dòng)

    import sys
    
    if not sys.warnoptions:
        import os, warnings
        warnings.simplefilter("default") # Change the filter in this process
        os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses
    
    0

    Chỉ in sự xuất hiện đầu tiên của các cảnh báo phù hợp, bất kể vị trí

  • Thông báo là một chuỗi chứa một biểu thức thông thường rằng việc bắt đầu thông báo cảnh báo phải khớp, không nhạy cảm với trường hợp. Trong

    import sys
    
    if not sys.warnoptions:
        import os, warnings
        warnings.simplefilter("default") # Change the filter in this process
        os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses
    
    1 và
    import sys
    
    if not sys.warnoptions:
        import os, warnings
        warnings.simplefilter("default") # Change the filter in this process
        os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses
    
    2, tin nhắn là một chuỗi theo nghĩa đen mà bắt đầu thông báo cảnh báo phải chứa (không nhạy cảm với trường hợp), bỏ qua bất kỳ khoảng trắng nào khi bắt đầu hoặc kết thúc tin nhắn.
    import sys
    
    if not sys.warnoptions:
        import os, warnings
        warnings.simplefilter("default") # Change the filter in this process
        os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses
    
    2, message is a literal string that the start of the warning message must contain (case-insensitively), ignoring any whitespace at the start or end of message.

  • Danh mục là một lớp (một lớp con của

    default                      # Show all warnings (even those ignored by default)
    ignore                       # Ignore all warnings
    error                        # Convert all warnings to errors
    error::ResourceWarning       # Treat ResourceWarning messages as errors
    default::DeprecationWarning  # Show DeprecationWarning messages
    ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
    error:::mymodule             # Convert warnings to errors in "mymodule"
    
    6) trong đó danh mục cảnh báo phải là một lớp con để phù hợp.

  • Mô-đun là một chuỗi chứa một biểu thức chính quy mà việc bắt đầu tên mô-đun đủ điều kiện phải khớp, nhạy cảm với trường hợp. Trong

    import sys
    
    if not sys.warnoptions:
        import os, warnings
        warnings.simplefilter("default") # Change the filter in this process
        os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses
    
    1 và
    import sys
    
    if not sys.warnoptions:
        import os, warnings
        warnings.simplefilter("default") # Change the filter in this process
        os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses
    
    2, mô-đun là một chuỗi theo nghĩa đen mà tên mô-đun đủ điều kiện phải bằng (nhạy cảm với trường hợp), bỏ qua bất kỳ khoảng trắng nào khi bắt đầu hoặc kết thúc mô-đun.
    import sys
    
    if not sys.warnoptions:
        import os, warnings
        warnings.simplefilter("default") # Change the filter in this process
        os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses
    
    2, module is a literal string that the fully qualified module name must be equal to (case-sensitively), ignoring any whitespace at the start or end of module.

  • Lineno là một số nguyên mà số dòng nơi cảnh báo xảy ra phải khớp hoặc

    import sys
    
    if not sys.warnoptions:
        import os, warnings
        warnings.simplefilter("default") # Change the filter in this process
        os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses
    
    6 để khớp với tất cả các số dòng.

Vì lớp

default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
6 có nguồn gốc từ lớp
default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
8 tích hợp, để biến cảnh báo thành lỗi, chúng tôi chỉ cần tăng
import sys

if not sys.warnoptions:
    import os, warnings
    warnings.simplefilter("default") # Change the filter in this process
    os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses
9.

Nếu một cảnh báo được báo cáo và không phù hợp với bất kỳ bộ lọc đã đăng ký nào thì hành động mặc định của Cameron được áp dụng (do đó tên của nó).

Mô tả các bộ lọc cảnh báo

Bộ lọc cảnh báo được khởi tạo bằng các tùy chọn

import sys

if not sys.warnoptions:
    import os, warnings
    warnings.simplefilter("default") # Change the filter in this process
    os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses
1 được chuyển cho dòng lệnh phiên dịch Python và biến môi trường
import sys

if not sys.warnoptions:
    import os, warnings
    warnings.simplefilter("default") # Change the filter in this process
    os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses
2. Thông dịch viên lưu các đối số cho tất cả các mục được cung cấp mà không cần giải thích trong
import warnings
warnings.filterwarnings("default", category=DeprecationWarning,
                                   module=user_ns.get("__name__"))
2; Mô -đun
import warnings
warnings.filterwarnings("default", category=DeprecationWarning,
                                   module=user_ns.get("__name__"))
3 phân tích các phân tích chúng khi nó được nhập lần đầu tiên (các tùy chọn không hợp lệ bị bỏ qua, sau khi in một thông báo đến
default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
1).
import sys

if not sys.warnoptions:
    import os, warnings
    warnings.simplefilter("default") # Change the filter in this process
    os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses
2 environment variable. The interpreter saves the arguments for all supplied entries without interpretation in
import warnings
warnings.filterwarnings("default", category=DeprecationWarning,
                                   module=user_ns.get("__name__"))
2; the
import warnings
warnings.filterwarnings("default", category=DeprecationWarning,
                                   module=user_ns.get("__name__"))
3 module parses these when it is first imported (invalid options are ignored, after printing a message to
default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
1).

Các bộ lọc cảnh báo riêng lẻ được chỉ định là một chuỗi các trường được phân tách bởi các dấu chấm câu:

action:message:category:module:line

Ý nghĩa của từng trường này được mô tả trong bộ lọc cảnh báo. Khi liệt kê nhiều bộ lọc trên một dòng (như đối với

import sys

if not sys.warnoptions:
    import os, warnings
    warnings.simplefilter("default") # Change the filter in this process
    os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses
2), các bộ lọc riêng lẻ được phân tách bằng dấu phẩy và các bộ lọc được liệt kê sau đó được ưu tiên hơn các bộ lọc được liệt kê trước chúng (khi chúng được áp dụng từ trái sang phải và được áp dụng gần đây nhất Bộ lọc được ưu tiên hơn so với những cái trước đó).The Warnings Filter. When listing multiple filters on a single line (as for
import sys

if not sys.warnoptions:
    import os, warnings
    warnings.simplefilter("default") # Change the filter in this process
    os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses
2), the individual filters are separated by commas and the filters listed later take precedence over those listed before them (as they’re applied left-to-right, and the most recently applied filters take precedence over earlier ones).

Các bộ lọc cảnh báo thường được sử dụng áp dụng cho tất cả các cảnh báo, cảnh báo trong một danh mục cụ thể hoặc cảnh báo được đưa ra bởi các mô -đun hoặc gói cụ thể. Vài ví dụ:

default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"

Bộ lọc cảnh báo mặc định

Theo mặc định, Python cài đặt một số bộ lọc cảnh báo, có thể được ghi đè bởi tùy chọn dòng lệnh

import sys

if not sys.warnoptions:
    import os, warnings
    warnings.simplefilter("default") # Change the filter in this process
    os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses
1, biến môi trường
import sys

if not sys.warnoptions:
    import os, warnings
    warnings.simplefilter("default") # Change the filter in this process
    os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses
2 và gọi đến
default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
2.
import sys

if not sys.warnoptions:
    import os, warnings
    warnings.simplefilter("default") # Change the filter in this process
    os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses
2 environment variable and calls to
default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
2.

Trong các bản dựng phát hành thường xuyên, bộ lọc cảnh báo mặc định có các mục sau (theo thứ tự ưu tiên):

default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning

Trong bản dựng gỡ lỗi, danh sách các bộ lọc cảnh báo mặc định trống rỗng.debug build, the list of default warning filters is empty.

Đã thay đổi trong phiên bản 3.7:

default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
1 một lần nữa được hiển thị theo mặc định khi được kích hoạt trực tiếp bằng mã trong
default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
2.
default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
1 is once again shown by default when triggered directly by code in
default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
2.

Đã thay đổi trong phiên bản 3.7:

default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
9 không còn xuất hiện trong danh sách bộ lọc mặc định và thay vào đó được cấu hình qua
import warnings
warnings.filterwarnings("default", category=DeprecationWarning,
                                   module=user_ns.get("__name__"))
2 khi
import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    fxn()
3 được chỉ định hai lần.
default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
9 no longer appears in the default filter list and is instead configured via
import warnings
warnings.filterwarnings("default", category=DeprecationWarning,
                                   module=user_ns.get("__name__"))
2 when
import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    fxn()
3 is specified twice.

Ghi đè bộ lọc mặc định

Các nhà phát triển các ứng dụng được viết bằng Python có thể muốn ẩn tất cả các cảnh báo cấp độ Python khỏi người dùng của họ theo mặc định và chỉ hiển thị chúng khi chạy thử nghiệm hoặc làm việc trên ứng dụng. Thuộc tính

import warnings
warnings.filterwarnings("default", category=DeprecationWarning,
                                   module=user_ns.get("__name__"))
2 được sử dụng để truyền cấu hình bộ lọc cho trình thông dịch có thể được sử dụng làm điểm đánh dấu để cho biết liệu cảnh báo có nên bị vô hiệu hóa hay không:

import sys

if not sys.warnoptions:
    import warnings
    warnings.simplefilter("ignore")

Thay vào đó, các nhà phát triển của các vận động viên kiểm tra cho mã Python được khuyên nên đảm bảo rằng tất cả các cảnh báo được hiển thị theo mặc định cho mã được kiểm tra, sử dụng mã như:

import sys

if not sys.warnoptions:
    import os, warnings
    warnings.simplefilter("default") # Change the filter in this process
    os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses

Cuối cùng, các nhà phát triển các shell tương tác chạy mã người dùng trong không gian tên khác với

default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
2 nên đảm bảo rằng các thông báo
default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
1 được hiển thị theo mặc định, sử dụng mã như sau (trong đó
import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    fxn()
7 là mô -đun được sử dụng để thực thi mã được nhập một cách tương tác):

import warnings
warnings.filterwarnings("default", category=DeprecationWarning,
                                   module=user_ns.get("__name__"))

Tạm thời triệt tiêu cảnh báo Jo

Nếu bạn đang sử dụng mã mà bạn biết sẽ đưa ra cảnh báo, chẳng hạn như hàm không dùng Trình quản lý bối cảnh

import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    fxn()
8:

import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    fxn()

Trong khi trong Trình quản lý bối cảnh, tất cả các cảnh báo sẽ đơn giản bị bỏ qua. Điều này cho phép bạn sử dụng mã đã biết đã biết mà không phải xem cảnh báo trong khi không triệt tiêu cảnh báo cho mã khác có thể không nhận thức được việc sử dụng mã bị mất. Lưu ý: Điều này chỉ có thể được đảm bảo trong một ứng dụng đơn luồng. Nếu hai hoặc nhiều luồng sử dụng trình quản lý bối cảnh

import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    fxn()
8 cùng một lúc, hành vi không được xác định.

Kiểm tra cảnh báo

Để kiểm tra các cảnh báo được đưa ra bởi mã, hãy sử dụng Trình quản lý bối cảnh

import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    fxn()
8. Với nó, bạn có thể tạm thời đột biến bộ lọc cảnh báo để tạo điều kiện cho thử nghiệm của bạn. Chẳng hạn, hãy làm như sau để nắm bắt tất cả các cảnh báo tăng lên để kiểm tra:

import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings(record=True) as w:
    # Cause all warnings to always be triggered.
    warnings.simplefilter("always")
    # Trigger a warning.
    fxn()
    # Verify some things
    assert len(w) == 1
    assert issubclass(w[-1].category, DeprecationWarning)
    assert "deprecated" in str(w[-1].message)

Người ta cũng có thể khiến tất cả các cảnh báo là ngoại lệ bằng cách sử dụng

import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings(record=True) as w:
    # Cause all warnings to always be triggered.
    warnings.simplefilter("always")
    # Trigger a warning.
    fxn()
    # Verify some things
    assert len(w) == 1
    assert issubclass(w[-1].category, DeprecationWarning)
    assert "deprecated" in str(w[-1].message)
1 thay vì
import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings(record=True) as w:
    # Cause all warnings to always be triggered.
    warnings.simplefilter("always")
    # Trigger a warning.
    fxn()
    # Verify some things
    assert len(w) == 1
    assert issubclass(w[-1].category, DeprecationWarning)
    assert "deprecated" in str(w[-1].message)
2. Một điều cần lưu ý là nếu một cảnh báo đã được nêu ra vì quy tắc ____ 73/________ 74, thì bất kể bộ lọc nào được đặt ra, cảnh báo sẽ không được nhìn thấy nữa trừ khi sổ đăng ký cảnh báo liên quan đến cảnh báo đã bị xóa.

Khi trình quản lý bối cảnh thoát ra, bộ lọc cảnh báo được khôi phục về trạng thái của nó khi bối cảnh được nhập. Điều này ngăn chặn các thử nghiệm thay đổi bộ lọc cảnh báo theo những cách bất ngờ giữa các thử nghiệm và dẫn đến kết quả kiểm tra không xác định. Hàm

default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
4 trong mô -đun cũng được khôi phục về giá trị ban đầu của nó. Lưu ý: Điều này chỉ có thể được đảm bảo trong một ứng dụng đơn luồng. Nếu hai hoặc nhiều luồng sử dụng trình quản lý bối cảnh
import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    fxn()
8 cùng một lúc, hành vi không được xác định.

Khi kiểm tra nhiều hoạt động nêu cùng một loại cảnh báo, điều quan trọng là phải kiểm tra chúng theo cách xác nhận mỗi thao tác đang đưa ra cảnh báo mới (ví dụ: đặt cảnh báo được nêu ra dưới dạng ngoại lệ và kiểm tra các hoạt động tăng ngoại lệ, hãy kiểm tra xem độ dài của danh sách cảnh báo tiếp tục tăng sau mỗi hoạt động, hoặc nếu không xóa các mục trước đó khỏi danh sách cảnh báo trước mỗi hoạt động mới).

Cập nhật mã cho các phiên bản mới của phụ thuộc

Các danh mục cảnh báo chủ yếu được các nhà phát triển Python quan tâm (thay vì người dùng cuối của các ứng dụng được viết bằng Python) bị bỏ qua theo mặc định.

Đáng chú ý, danh sách này bị bỏ qua bởi danh sách mặc định, bao gồm

default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
1 (đối với mọi mô -đun ngoại trừ
default::DeprecationWarning:__main__
ignore::DeprecationWarning
ignore::PendingDeprecationWarning
ignore::ImportWarning
ignore::ResourceWarning
2), có nghĩa là các nhà phát triển nên đảm bảo kiểm tra mã của họ với các cảnh báo thường bị bỏ qua để nhận được thông báo kịp thời về các thay đổi API trong tương lai (cho dù trong Thư viện tiêu chuẩn hoặc gói bên thứ ba).

Trong trường hợp lý tưởng, mã sẽ có bộ thử nghiệm phù hợp và người chạy thử nghiệm sẽ chăm sóc cho phép hoàn toàn cho phép tất cả các cảnh báo khi chạy thử nghiệm (người chạy thử nghiệm được cung cấp bởi mô -đun ____79 thực hiện điều này).

Trong các trường hợp ít lý tưởng hơn, các ứng dụng có thể được kiểm tra để sử dụng các giao diện không dùng nữa bằng cách chuyển

def deprecation(message):
    warnings.warn(message, DeprecationWarning, stacklevel=2)
0 cho trình thông dịch Python (đây là tốc ký cho
def deprecation(message):
    warnings.warn(message, DeprecationWarning, stacklevel=2)
1) hoặc đặt
def deprecation(message):
    warnings.warn(message, DeprecationWarning, stacklevel=2)
2 trong môi trường. Điều này cho phép xử lý mặc định cho tất cả các cảnh báo, bao gồm cả những cảnh báo bị bỏ qua theo mặc định. Để thay đổi hành động nào được thực hiện đối với các cảnh báo gặp phải, bạn có thể thay đổi đối số nào được chuyển sang
import sys

if not sys.warnoptions:
    import os, warnings
    warnings.simplefilter("default") # Change the filter in this process
    os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses
1 (ví dụ:
def deprecation(message):
    warnings.warn(message, DeprecationWarning, stacklevel=2)
4). Xem cờ
import sys

if not sys.warnoptions:
    import os, warnings
    warnings.simplefilter("default") # Change the filter in this process
    os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses
1 để biết thêm chi tiết về những gì có thể.

Chức năng có sẵn

cảnh báo.warn (tin nhắn, danh mục = none, stacklevel = 1, nguồn = không) ¶warn(message, category=None, stacklevel=1, source=None)

Đưa ra cảnh báo, hoặc có thể bỏ qua nó hoặc nêu ra một ngoại lệ. Đối số danh mục, nếu được đưa ra, phải là một lớp loại cảnh báo; Nó mặc định là

default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
9. Ngoài ra, tin nhắn có thể là một ví dụ
default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
6, trong trường hợp đó, danh mục sẽ bị bỏ qua và
def deprecation(message):
    warnings.warn(message, DeprecationWarning, stacklevel=2)
8 sẽ được sử dụng. Trong trường hợp này, văn bản tin nhắn sẽ là
def deprecation(message):
    warnings.warn(message, DeprecationWarning, stacklevel=2)
9. Hàm này làm tăng một ngoại lệ nếu cảnh báo cụ thể được đưa ra được thay đổi thành lỗi bởi bộ lọc cảnh báo. Đối số Stacklevel có thể được sử dụng bởi các chức năng bao bọc được viết bằng Python, như thế này:warning category class; it defaults to
default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
9. Alternatively, message can be a
default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
6 instance, in which case category will be ignored and
def deprecation(message):
    warnings.warn(message, DeprecationWarning, stacklevel=2)
8 will be used. In this case, the message text will be
def deprecation(message):
    warnings.warn(message, DeprecationWarning, stacklevel=2)
9. This function raises an exception if the particular warning issued is changed into an error by the warnings filter. The stacklevel argument can be used by wrapper functions written in Python, like this:

def deprecation(message):
    warnings.warn(message, DeprecationWarning, stacklevel=2)

Điều này làm cho cảnh báo đề cập đến người gọi ____ ____ 90, thay vì nguồn gốc của chính warn()0 (vì sau này sẽ đánh bại mục đích của thông điệp cảnh báo).

Nguồn, nếu được cung cấp, là đối tượng bị phá hủy phát ra

import sys

if not sys.warnoptions:
    import warnings
    warnings.simplefilter("ignore")
2.

Đã thay đổi trong phiên bản 3.6: Thêm tham số nguồn.Added source parameter.

cảnh báo.warn_explicit (tin nhắn, danh mục, tên tệp, lineno, module = none, registry = none, module_globals = none, source = none) ¶warn_explicit(message, category, filename, lineno, module=None, registry=None, module_globals=None, source=None)

Đây là giao diện cấp thấp đối với chức năng của warn(), chuyển qua rõ ràng thông điệp, danh mục, tên tệp và số dòng, và tùy chọn tên mô-đun và sổ đăng ký (phải là từ điển warn()4 của mô-đun). Tên mô -đun mặc định là tên tệp với warn()5 bị tước; Nếu không có sổ đăng ký được thông qua, cảnh báo không bao giờ bị đàn áp. Thông báo phải là một chuỗi và loại Một lớp con của

default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
6 hoặc thông báo có thể là một ví dụ
default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
6, trong trường hợp đó, danh mục sẽ bị bỏ qua.

Module_Globals, nếu được cung cấp, nên là không gian tên toàn cầu được sử dụng bởi mã mà cảnh báo được ban hành. .

Nguồn, nếu được cung cấp, là đối tượng bị phá hủy phát ra

import sys

if not sys.warnoptions:
    import warnings
    warnings.simplefilter("ignore")
2.

Đã thay đổi trong phiên bản 3.6: Thêm tham số nguồn.Add the source parameter.

cảnh báo.warn_explicit (tin nhắn, danh mục, tên tệp, lineno, module = none, registry = none, module_globals = none, source = none) ¶showwarning(message, category, filename, lineno, file=None, line=None)

Đây là giao diện cấp thấp đối với chức năng của warn(), chuyển qua rõ ràng thông điệp, danh mục, tên tệp và số dòng, và tùy chọn tên mô-đun và sổ đăng ký (phải là từ điển warn()4 của mô-đun). Tên mô -đun mặc định là tên tệp với warn()5 bị tước; Nếu không có sổ đăng ký được thông qua, cảnh báo không bao giờ bị đàn áp. Thông báo phải là một chuỗi và loại Một lớp con của

default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
6 hoặc thông báo có thể là một ví dụ
default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
6, trong trường hợp đó, danh mục sẽ bị bỏ qua.

cảnh báo.formatwarning (tin nhắn, danh mục, tên tệp, lineno, line = none) ¶formatwarning(message, category, filename, lineno, line=None)

Định dạng một cảnh báo theo cách tiêu chuẩn. Điều này trả về một chuỗi có thể chứa các dòng mới được nhúng và kết thúc trong một dòng mới. Dòng là một dòng mã nguồn được đưa vào thông báo cảnh báo; Nếu dòng không được cung cấp,

default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
5 sẽ cố gắng đọc dòng được chỉ định bởi FileName và Lineno.

cảnh báo.filterWarnings (hành động, message = '', category = cảnh báo, mô -đun = '', lineno = 0, append = false)filterwarnings(action, message='', category=Warning, module='', lineno=0, append=False)

Chèn một mục vào danh sách các thông số kỹ thuật của bộ lọc cảnh báo. Mục nhập được chèn ở phía trước theo mặc định; Nếu phần nối là đúng, nó được chèn vào cuối. Điều này kiểm tra các loại của các đối số, biên dịch các biểu thức thông báo và mô -đun thông thường và chèn chúng dưới dạng một bộ trong danh sách các bộ lọc cảnh báo. Các mục gần hơn với mặt trước của danh sách ghi đè các mục sau trong danh sách, nếu cả hai đều khớp với một cảnh báo cụ thể. Bỏ qua đối số mặc định với một giá trị phù hợp với mọi thứ.warnings filter specifications. The entry is inserted at the front by default; if append is true, it is inserted at the end. This checks the types of the arguments, compiles the message and module regular expressions, and inserts them as a tuple in the list of warnings filters. Entries closer to the front of the list override entries later in the list, if both match a particular warning. Omitted arguments default to a value that matches everything.

cảnh báo.simplefilter (hành động, danh mục = cảnh báo, lineno = 0, append = false) ¶simplefilter(action, category=Warning, lineno=0, append=False)

Chèn một mục đơn giản vào danh sách các thông số kỹ thuật của bộ lọc cảnh báo. Ý nghĩa của các tham số chức năng là đối với

default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
2, nhưng các biểu thức chính quy là không cần thiết vì bộ lọc được chèn luôn khớp với bất kỳ thông báo nào trong bất kỳ mô -đun nào miễn là khớp số và số dòng khớp.warnings filter specifications. The meaning of the function parameters is as for
default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
2, but regular expressions are not needed as the filter inserted always matches any message in any module as long as the category and line number match.

cảnh báo.resetwarnings () ¶resetwarnings()

Đặt lại bộ lọc cảnh báo. Điều này loại bỏ hiệu ứng của tất cả các cuộc gọi trước đó đến

default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
2, bao gồm các tùy chọn dòng lệnh
import sys

if not sys.warnoptions:
    import os, warnings
    warnings.simplefilter("default") # Change the filter in this process
    os.environ["PYTHONWARNINGS"] = "default" # Also affect subprocesses
1 và các cuộc gọi đến
default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
07.

Người quản lý bối cảnh có sẵn

Classwarnings.catch_warnings (*, record = false, module = none, action = none, category = warning, lineno = 0, append = false)warnings.catch_warnings(*, record=False, module=None, action=None, category=Warning, lineno=0, append=False)

Trình quản lý bối cảnh sao chép và, khi thoát, khôi phục bộ lọc cảnh báo và hàm

default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
4. Nếu đối số bản ghi là
default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
09 (mặc định), trình quản lý bối cảnh trả về
default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
10 khi nhập. Nếu bản ghi là
default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
11, một danh sách được trả về dần dần có các đối tượng được nhìn thấy bởi hàm
default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
4 tùy chỉnh (cũng triệt tiêu đầu ra thành
default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
13). Mỗi đối tượng trong danh sách có các thuộc tính có cùng tên với các đối số với
default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
4.

Đối số mô -đun lấy một mô -đun sẽ được sử dụng thay vì mô -đun được trả về khi bạn nhập

import warnings
warnings.filterwarnings("default", category=DeprecationWarning,
                                   module=user_ns.get("__name__"))
3 có bộ lọc sẽ được bảo vệ. Đối số này tồn tại chủ yếu để kiểm tra mô -đun
import warnings
warnings.filterwarnings("default", category=DeprecationWarning,
                                   module=user_ns.get("__name__"))
3.

Nếu đối số hành động không phải là

default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
10, các đối số còn lại được chuyển đến
default                      # Show all warnings (even those ignored by default)
ignore                       # Ignore all warnings
error                        # Convert all warnings to errors
error::ResourceWarning       # Treat ResourceWarning messages as errors
default::DeprecationWarning  # Show DeprecationWarning messages
ignore,default:::mymodule    # Only report warnings triggered by "mymodule"
error:::mymodule             # Convert warnings to errors in "mymodule"
07 như thể nó được gọi ngay lập tức khi vào bối cảnh.

Ghi chú

Trình quản lý

import warnings

def fxn():
    warnings.warn("deprecated", DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter("ignore")
    fxn()
8 hoạt động bằng cách thay thế và sau đó khôi phục chức năng mô -đun ____ ____ ____ và danh sách nội bộ của các thông số kỹ thuật của bộ lọc. Điều này có nghĩa là Trình quản lý bối cảnh đang sửa đổi trạng thái toàn cầu và do đó không an toàn cho luồng.

Đã thay đổi trong phiên bản 3.11: Đã thêm các tham số hành động, danh mục, lineno và phụ lục.Added the action, category, lineno, and append parameters.

Làm thế nào để bạn cho thấy cảnh báo trong Python?

Hàm cảnh báo () được xác định trong mô -đun 'cảnh báo' được sử dụng để hiển thị các thông điệp cảnh báo.Mô-đun cảnh báo thực sự là một lớp ngoại lệ là một lớp tích hợp trong Python. is used to show warning messages. The warning module is actually a subclass of Exception which is a built-in class in Python.

Làm thế nào để bạn không hiển thị các thông điệp cảnh báo trong Python?

Làm thế nào để đàn áp các thông điệp cảnh báo trong Python..
Xây dựng vấn đề và tổng quan về giải pháp ..
Phương pháp 1: CẢNH BÁO CẢNH BÁO với FilterWarnings ().
Phương pháp 2: Tho bỏ các cảnh báo cụ thể với FilterWarnings ().
Phương pháp 3: Bị cảnh báo với Catch_warnings ().
Phương pháp 4: Bị cảnh báo với Shutup ().
Phương pháp 5: Bị cảnh báo với -W ..

Làm thế nào để bạn xử lý một cảnh báo thời gian chạy trong Python?

Khi bạn thực sự có một cảnh báo, bạn có thể sử dụng mô -đun cảnh báo để kiểm soát cách các cảnh báo nên được xử lý: >>> Cảnh báo nhập khẩu >>> >>> cảnh báo.FilterWarnings ('Lỗi') >>> >>> Hãy thử: ... Cảnh báo.use the warnings module to control how the warnings should be treated: >>> import warnings >>> >>> warnings. filterwarnings('error') >>> >>> try: ... warnings.