2

To python experts: I put lots of print() to check the value of my variables. Once I'm done, I need to delete the print(). It quite time-consuming and prompt to human errors.

Would like to learn how do you guys deal with print(). Do you delete it while coding or delete it at the end? Or there is a method to delete it automatically or you don't use print()to check the variable value?

Lisa
  • 4,126
  • 12
  • 42
  • 71
  • I highly recommend using the standard logging module. You can set various log levels (DEBUG, INFO, WARNING, ERROR, CRITICAL). This allows one to filter by level the output the program will generate. Between this and interactive debugging, there's not alot of use for the standard "print" at an intermediary/expert level – A Small Shell Script Aug 09 '16 at 04:12

3 Answers3

4

Use logging instead and here is why.
logging module comes with many simple & handy log methods like debug, info, warning, error, critical
ex:- logging.debug(<debug stuff>)
EDIT I am not sure I understood correctly about your need to disable logging once you are done, but if you want to do away with console logging you can try

#logger = logging.getLogger() # this gets the root logger
logger = logging.getLogger('my-logger')
logger.propagate = False
# now if you use logger it will not log to console.

EDIT
I think you want to remove all your print()/loggging statements from your code once you make sure everything is working fine!!!!
Try using a regx to comment out all print statements

find . -name '<filename>.py' -exec sed -ri "s/(^\s*)(print.*$)/#\1\2/g" {} \;
Tony Vincent
  • 13,354
  • 7
  • 49
  • 68
  • Thank. But how do I remove the logging.debug message once im done?@Tony Vincent – Lisa Aug 09 '16 at 04:25
  • Please explain what exactly you mean 'once I am done' !! – Tony Vincent Aug 09 '16 at 04:35
  • How do I disable the logging.debug message printed to screen when I don't want to see these message? Example: I want to do print(df.head) , print(df.tail) and print(df.describe()). Once I know what the df looks like, I delete print() manually. If I use logging, I will put logging.debug(print(df.head)) instead, if I understand it correctly. So what is the equivalent of deleting print()? @Tony Vincent – Lisa Aug 09 '16 at 04:54
  • Thanks. So my final script will end up with lots of logging.debug() and logging.ingo()? Wouldn't this reduce the readability of the script?@Tony Vincent – Lisa Aug 09 '16 at 05:45
2

You can use logging with debug level and once the debugging is completed, change the level to info. So any statements with logger.debug() will not be printed.

0

What I do is put print statements in with with a special text marker in the string. I usually use print("XXX", thething). Then I just search for and delete the line with that string. It's also easier to spot in the output.

Keith
  • 42,110
  • 11
  • 57
  • 76