How to do debug prints?

I’m new to programing and was wondering if there is a best practice for turning on debug printing. Currently I just use a variable and if statements before each print statement that I don’t want the user to see, but that causes there to be a lot of if statements. Is there a better way to do this?

debug = False

# A few lines later(French accent)

if debug:
    print(links)

I comment out debug statements for production version, and uncomment as needed if something is not working correctly.

You can write to revit journal, or dedicated debug log to a file if you want to check the output later.

Or set up different levels using mlogger, and then when you want to display or hide output you can change the logging level in pyrevit settings

1 Like

pyRevit has a native debug feature by holding ‘Ctrl’ while clicking a pushbutton.

This works great for me, as I can see debug if I need, but it is not displayed as default.

Sample use:

from pyrevit import script, revit

# Initialize logging for debug mode (triggered with Ctrl + click)
logger = script.get_logger()

# Sample logging within a transaction
with revit.Transaction('Sample Transaction'):
    logger.debug("Starting transaction...")

You can use different levels of logging like logger.error, logger.info etc.

(This is from memory, so there might be typos :sweat_smile:)

1 Like

Rather than many if statements, it is much easier to create a toggleable print function like so:

GLOBAL_DEBUG = True
def p(*to_print): # Toggleable print function. Turn on to debug.
	if GLOBAL_DEBUG:
		for item in to_print:
			print item

p('Data to check:', some_variable_to_check, another_variable_to_check)

This works quite well for me. I have tried to use pyRevit’s logger, but it always printed out WAY too much info, most of it regarding the inner workings of pyRevit, which are irrelevant to me. It would also take almost a minute to finish printing.

You can leave these calls to the print function all throughout your code and only turn on GLOBAL_DEBUG when you need to diagnose a problem.

To me, this is more efficient than commenting out the print statements. Then, you would need to un-comment all the print statements in the whole document to see the full workings. Also, I don’t think code should be commented-out permanently. It is very distracting, sloppy, and hard to read. (not that I follow my own advice…)

1 Like

Just write perfect code and eliminate the debugging. problem solved :innocent:

1 Like

Doh! Why didn’t I think of that! :man_facepalming: