import warnings
warnings.warn("Warning...........Message")
See the python documentation: here
Answer from necromancer on Stack Overflowpython - Print only the message on warnings - Stack Overflow
How to raise a warning in Python without interrupting execution? - Ask a Question - TestMu AI Community
Python warning message output - Stack Overflow
Default warning formatting improvements - Ideas - Discussions on Python.org
To suppress warnings, I used the python warnings module.
# this should be at the very top of the file
import warnings
warnings.filterwarnings("ignore")
# the rest of the code, including all other import statements, goes here
Now, it only prints out errors and whatever I want it to output.
Since the question is actually about ignoring Python warnings (which are usually there for a reason), reading the documentation actually yields the nice and concise python - Wignore which avoids having to modify (potentially third-party) code.
There is always monkeypatching:
import warnings
def custom_formatwarning(msg, *args, **kwargs):
# ignore everything except the message
return str(msg) + '\n'
warnings.formatwarning = custom_formatwarning
warnings.warn("achtung")
Monkeypatch warnings.showwarning() with your own custom function.
The globals aren't doing much for you, so get rid of them.
Your code will not do the right thing if an argument fails to print: the colour will not be reset. Add a finally to handle this case.
You're too aggressive with your style reset. Just reset the fore colour and nothing else.
Add type hints.
am I horribly misusing
*arg?
No, it's fine.
is it okay to use PASS as a variable, as lower-case pass is a reserved word?
Not really. The convention to get around keywords is an underscore suffix, as in pass_.
from typing import Any
import colorama
def print_colour(fore_colour: str, *text: Any) -> None:
print(fore_colour, end='')
try:
print(*text, end='')
finally:
print(colorama.Fore.RESET)
def okay(*text: Any) -> None:
print_colour(colorama.Fore.GREEN, *text)
def warn(*text: Any) -> None:
print_colour(colorama.Fore.YELLOW, *text)
def fail(*text: Any) -> None:
print_colour(colorama.Fore.RED, *text)
def test() -> None:
class BadClass:
def __str__(self):
raise ValueError()
try:
fail(BadClass())
except ValueError:
pass
print('Should be in default colour')
warn("Unfragmented text")
warn("Fragmented", "text")
fail("Unfragmented text")
fail("Fragmented", "text")
okay("Unfragmented text")
okay("Fragmented", "text")
if __name__ == '__main__':
test()
am I horribly misusing *arg? I've never used it before, and so often stuff that just works can backfire in unexpected ways once I try to get it to do more.
I wouldn't say you are misusing it (though my preference would be to make the caller provide a sequence in every situation), but you are overusing it. Every one of your functions assumes it will receive at least one argument, so you should formalize that with a required first parameter.
For example,
def warn(first, *txt):
a = list(txt)
first = WARN + first
a[-1] += WTXT
print(first, *a)
I am writing a mini-program for basic payment calculation, and after the calculation the results are printed in the terminal. However, I get the following warnings from Ruff (the Python linter that I use):
src/pf_example/food_payment.py:39:5: T201 print found src/pf_example/food_payment.py:51:5: T201 print found src/pf_example/food_payment.py:52:5: T201 print found src/pf_example/food_payment.py:54:5: T201 print found src/pf_example/food_payment.py:56:9: T201 print found
I know that I can turn off this check in the settings, BUT I don't why print is bad in the code. What would be the alternatives if not using print?
The reference manual is a great source. For the warnings module, it says:
The printing of warning messages is done by calling
showwarning(), which may be overridden
And later:
warnings.showwarning(message, category, filename, lineno, file=None, line=None)... You may replace this function with any callable by assigning to
warnings.showwarning.
So just declare your own function special_showwarning with the same parameters, format the output the way you want and simply do: logging.showwarning = special_showwarning.
An equivalent way is possible for exception by overriding sys.excepthook:
sys.excepthook(type, value, traceback)This function prints out a given traceback and exception to sys.stderr.
When an exception is raised and uncaught, the interpreter calls sys.excepthook with three arguments... The handling of such top-level exceptions can be customized by assigning another three-argument function to sys.excepthook.
Unfortunately, this may not work when executing python code in an IDE, for example IDLE uses a custom loop and does not call sys.excepthook. In that case, you could simply wrap your current main in a try block and catch anything. It is then easy to display what you want:
def main():
# your code ...
if __name__ == '__main__':
try:
main()
except:
type, value, traceback = sys.exc_info()
# add your error formatting here
If you change your source code slightly to a real life situation it becomes maybe clearer why the behavior is like this:
import warnings
warn = 'This is a warning'
exception = 'This is an exception'
def main():
warnings.warn(warn)
raise RuntimeError(exception)
if __name__=='__main__':
main()
Now the output is:
test_exception.py:6: UserWarning: This is a warning
warnings.warn(warn)
Traceback (most recent call last):
File "C:\Users\11ldornbusch\Desktop\2del.py", line 10, in <module>
main()
File "C:\Users\11ldornbusch\Desktop\2del.py", line 7, in main
raise RuntimeError(exception)
RuntimeError: This is an exception
So if you use variables your output shows in one line the content of the variable, and in the other the name. This can give you more context on what the problem is, for example a "Nothing" as output will gives you also the name of the variable which is nothing.
You can also use logging or Hook the output in python to modify the output of the warning: From the documentation available here: https://docs.python.org/3/library/warnings.html
The printing of warning messages is done by calling showwarning(), which may be overridden; the default implementation of this function formats the message by calling formatwarning(), which is also available for use by custom implementations.