1. How to Debugging in python? Syntax and header errors are hard to catch unless you have access to the server logs. Syntax error messages can be seen if the script is run in a local shell before uploading to the server.
For a nice exceptions report there is the cgitb module. It will show a trace-back inside a context. The default output is sent to standard output as HTML:
#!/usr/bin/env python print "Content-Type: text/html" print import cgitb; cgitb. enable() print 1/0
The handler() method can be used to handle only the catched exceptions:
#!/usr/bin/env python print "Content-Type: text/html" print import cgitb try: f = open('non-existent-file. txt', 'r') except: cgitb. handler()
There is also the option for a crude approach making the header "text/plain" and setting the standard error to standard out:
#!/usr/bin/env python print "Content-Type: text/plain" print import sys sys. stderr = sys. stdout f = open('non-existent-file. txt', 'r')
Will output this:
Traceback (most recent call last): File "/var/www/html/teste/cgi-bin/text_error. py", line 6, in ? f = open('non-existent-file. txt', 'r') IOError: [Errno 2] No such file or directory: 'non-existent-file. txt'
Warning: These techniques expose information that can be used by an attacker. Use it only while developing/debugging. Once in production disable it. 2. How do you set a global variable in a function?
Did you do something like this? x = 1 # make a global def f(): print x # try to print the global . . . for j in range(100): if q>3: x=4
Any variable assigned in a function is local to that function. unless it is specifically declared global. Since a value is bound to x as the last statement of the function body, the compiler assumes that x is local. Consequently the print x attempts to print an uninitialized local variable and will trigger a NameError.
« Last Edit: May 12, 2011, 09:12:03 PM by Admin »
Sorry, but you are not allowed to view signatures , please Register or Login
|