How does one debug CGI more efficiently?

He has: 14 posts

Joined: Sep 2005

Hello there,

This is a rather general question, so I am open to different approaches. I'm learning python and trying out some things as CGI scripts that handle very simple html forms.

Is there a better way to find out exactly what went wrong with my python scripts (instead of guess-and-check from the HTML 500 (Internal Server Error) screens)? PHP shows you which line the error was on, so that's easy.

Is there a similar tool that allows easy debugging of CGI scripts? Or am I way off track here? I would really like to know.

Thanks in advance!

Greg K's picture

He has: 2,145 posts

Joined: Nov 2003

I'm not sure what all python has available, however as a general way to help figure things out, you can always output certain data to either the screen, or better, to a text file. Then you can follow the flow. Make sure to have each output indicate what line # it is, so you can find it easier. Then if a calculation goes wrong, you can see where the numbers went off. Or a more common thing, if an SQL statement isn't executing right, have the actual sql statement outputed so you can se exactly how it was formatted. (this really helps when things are like forgeting to quote something that should have quoptes and such)

I have a custom PHP debug script I use, the nice thing is php has the __FILE__ and __LINE__ variables to indicate current filename and line number that is being executed. I have functions that will output a whole array, etc.

If you do use something like this, I recommend you set a variable at the begining of the program to TRUE, (ie. in PHP I used $debugging = true;) then all output lines start the same (if ($debugging) debugout(__FILE__,__LINE__,"var1 = $var1");) so that on the final production copy, you can easiuly search to remove all of these lines.

It's the tired and true debugging, but if you have nothing else, it is beter than a 500 error and trial/error approach.

-Greg

Abhishek Reddy's picture

He has: 3,348 posts

Joined: Jul 2001

See here for some ideas:
Python CGI FAQ: How do I debug my scripts?

CGI traceback in Python

Guido's basic debugging framework for CGI

If you write the scripts with not-unreasonable abstraction and modularity, you could run them - or parts of them - with the Python interpreter in the shell or through your IDE. This will print thrown errors and tracebacks. You could use the Python debugger as well. For most of any CGI script, this must be possible, with simulated inputs and flow.

As a last resort, especially when you need to debug simple errors with HTTP inputs, you could use the techniques Greg described.

Smiling

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.