JaxonBP
JaxonBP

Reputation: 49

How to see errors or exceptions in a Python script?

I'm completely new to working with Python (I have a PHP background)

I'm used to PHP's Error Handling and Logging. Yet, with Python I'm getting a 500 Error on a very simple script that should work.

Is there a way to turn on Error Handling with Python? As 500 Error doesn't tell me much of anything, except that something is not right.

I have looked on the net for an answer to this, but I'm not finding a solution to what should be very obvious.

Upvotes: 4

Views: 15653

Answers (1)

K Z
K Z

Reputation: 30453

Your question is asking how to see errors or exceptions (not how to handle then, though of course you need to handle these errors as well), and from the 500 error and PHP background it seems to imply you are doing web programming with Python.

There are many ways to do so in Python, here is some that I tend to use:

  1. in production use logging module to log errors. There are lots of tools that can help you such as Sentry [source code here]. You can read more on logging here.
  2. in development, run your script with python -m pdb myscript.py which will start your script in debugger mode, then enter c (continue) to continue the script until error occurs, and now you will be able to see what the states are in the interactive PDB (Python debugger) prompt.
  3. in development, if you are using a framework (or your script) that relies on WSGI, you can use the graphical, interactive JavaScript based in-browser helper Werkzeug which allows you debug at every level of the call stack.

And, to point out the most obvious one, Python interpreter will print out the stack trace if the program crashes, for eg:

→ python -c 'pprint "hello"'
  File "<string>", line 1
    pprint "hello"
                 ^
SyntaxError: invalid syntax


# print.py is just one line: print 'hello world'
→ python print.py 
  File "print.py", line 1
    pprint 'hello world'
                       ^
SyntaxError: invalid syntax

UPDATE:

It seems like you aren't using any frameworks, and you are behind a host which from the look of it, didn't tell you how exactly it is serving your Python script. Now, since all you want is to see the stack trace in the browser, you can do the following based on what your hosts uses:

If your script is running behind a server via CGI, all you need to do is to use the Python cgitb module to print the stack trace on the HTML page:

import cgitb
cgitb.enable()

However, it is very likely the shared hosting you signed up is using mod_python with Apache, so turning on PythonDebug in the Apache config file should print the stack trace in the browser:

PythonDebug On

For Apache with mod_wsgi, there's a better article written than I could summarize here: mod_wsgi Debugging Techniques

Upvotes: 7

Related Questions