Freek
Freek

Reputation: 1189

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.

Upvotes: 4

Views: 2951

Answers (1)

C. Fennell
C. Fennell

Reputation: 1032

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

Upvotes: 8

Related Questions