Skip to content Skip to sidebar Skip to footer

Prevent Python From Printing Return Result

I have a function that both returns a value and does some printing. Schematically: def func(x): print 'You're using this function' return x**2 There are two different ways in wh

Solution 1:

Because you're running the code in the interactive interpreter, the return value will always be printed out. If you run the code in a script, the return value will not be printed.

In general there's not really a downside to having the return value printed, it is extremely useful for debugging. If you are expecting someone else to use your code, you shouldn't be running it in this manner anyway.


After your further edit, you might want to tailer the behaviour of your function based on whether or not it's being run in the interactive interpreter. See this question for further details: Tell if Python is in interactive mode

From the accepted answer there:

__main__.__file__ doesn't exist in the interactive interpreter:

import __main__ as main 
printhasattr(main, '__file__')

This also goes for code run via python -c, but not python -m.

You could decide not to return the values you are doing for instance. However, this doesn't really solve your problem.

What I would advise doing, although you could argue it'd make your program a little more clunky for the user, is define a display function, that would be called if your user wanted the pretty result table. Usage would then be

>>>display(ela_dist(c_voigt, rotate = True))

or something of the sort.

Post a Comment for "Prevent Python From Printing Return Result"