How can I see print() statements in behave (BDD)

from command line, you can use the following:

--no-capture for any stdout output to be printed immediately.

--no-capture-stderr for any stderr output to be printed immediately.


The first thing to do is to prevent capture of stdout (and maybe also stderr) as explained by Xuan or Ben.

However, there's a further complication that will stump people who are not aware of it. By default, behave outputs its report in color. This is problematic because the way it works is that when it runs a step, it first prints out the line of the step in a neutral color that indicates it does not yet know whether the step has passed or not. Once the step has finished, it uses escape codes to overwrite the previous line with a new color. If you don't do something to work around it, behave may simply overwrite what your print statement produced, and it may be difficult to figure out what happened.

In the following illustrations, I'm going to put the color in brackets at the end of the line. If you do not use print, the step "do something" would appear like this, before it is executed:

When do something [gray]

And once executed it would be replaced with a green line:

When do something [green]

behave outputs an escape sequence that makes the terminal go up and overwrite the line with a new color. No problem there.

If you put print "foo" in your step, the terminal would contain this, just before the step is completed:

When do something [gray]
foo

And then when the step completes successfully this is what you'd see on the terminal:

When do something [gray]
When do something [green]

The same escape sequence has caused behave to overwrite the output produced by the print statement.

I've used two methods to work around the issue in addition to turning off stdout capture:

  1. Use the --no-color option. This turns off the escape sequences and your print statements should produce visible output.

  2. Add a few extra newlines at the end of a print. So print "foo\n\n", for instance. behave will overwrite a useless blank line instead of overwriting the information you want. This is what I end up doing most often because I never invoke behave directly and adding a single additional option to behave's invocation, or editing a settings file is more cumbersome than just adding a few newlines to print.