I am working with code that throws a lot of (for me at the moment) useless warnings using the warnings
library. Reading (/scanning) the documentation I only found a way to disable warnings for single functions. But I don't want to change so much of the code.
Is there a flag like python -no-warning foo.py
?
What would you recommend?
Answers
To suppress warnings globally without modifying each function or part of the code, you can use a couple of approaches:
Command Line Option
You can run your Python script with the -W
option to ignore warnings:
python -W ignore foo.py
This will suppress all warnings. If you want to ignore specific types of warnings, you can adjust the -W
option accordingly. For example, to ignore DeprecationWarning
:
python -W ignore::DeprecationWarning foo.py
Environment Variable
You can also set an environment variable to ignore warnings:
PYTHONWARNINGS="ignore" python foo.py
This has the same effect as the -W ignore
option.
Within the Script
If you prefer to do it within the script itself, you can add the following lines at the top of your script:
import warnings
warnings.filterwarnings("ignore")
This will suppress all warnings for the entire script.
Specific Recommendations
- Temporary Suppression: If you're debugging or developing and need a cleaner output, using the
-W ignore
option or setting the environment variable is quick and non-intrusive. - Fine-Grained Control: For long-term or production code, you might want more control over which warnings to suppress. Using
warnings.filterwarnings()
within the script can help you be selective about which warnings to ignore. - Code Quality: Suppressing warnings can hide important information about potential issues in your code. It might be beneficial to review and address the warnings, especially if they indicate deprecations or other problems.
Choose the approach that best fits your current needs and workflow.