Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warnings module prints part of warning twice

If I use this code in a script:

import warnings
if True:
    warnings.warn(
        "The specified directory is not empty, and does not "
        "appear to contain a pipeline we can update. Exiting."
    )

I get this as output:

~ > create.py -p something -o .
somethings.py:58: UserWarning: The specified directory is not empty, and does not appear to contain a pipeline we can update. Exiting.
  "The specified directory is not empty, and does not"
~ >

Why is the The specified directory is not empty, and does not string printed again and how do I turn this off?

Best regards.

like image 905
Freek Avatar asked Sep 05 '25 06:09

Freek


1 Answers

Try this:

warnings.warn("The specified directory is not empty, and does not "
              "appear to contain a pipeline we can update. Exiting.", stacklevel=2)

This will give you the following warning:

sys:1: UserWarning: The specified directory is not empty, and does not appear to contain a pipeline we can update. Exiting.

Warnings default to stack level 1 which is why it is being repeated. Stack level one tells the user the exact line of code that the warning originated from, which is your warning function call line. So by putting it on stack level 2, it will not show the line of the warning, and just the warning itself.

If you are interested in customizing the warning output more, you can use the warnings.warn_explicit() function.

https://docs.python.org/3.6/library/warnings.html#available-functions

like image 110
C. Fennell Avatar answered Sep 07 '25 20:09

C. Fennell