How to suppress warnings in Python


The warnings issued from calling the warn() function can be suppressed by adding the -W flag from the terminal or by calling the simplefilter() method.

This tutorial shows how you can supress Python warnings in practice.

1. Adding the -W flag when running Python script

When you run a .py script, you can add the -W flag and set the argument to ignore as follows:

python -W ignore main.py

By adding the -W ignore option, all warnings in the main.py script will be ignored.

2. Using the warnings module

You can suppress warnings by calling the warnings.simplefilter() method and instruct Python to ignore the warnings.

Consider the following code:

import sys
import warnings

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

The sys.warnoptions is used so that the -W flag you add when running the script takes precedence over the simplefilter() method.

If you set the -W flag, then the simplefilter() method won’t be called.

And that’s how you supress warnings when running Python code. Nice work! 👍

Level up your programming skills

I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.