One great thing about Python is the interactive debugger, which lets you inspect the value of variables at the point an error occurred. Of course, IPython integrates nicely with the Python debugger and makes debugging code a cinch.
| xmode Plain | plain exception mode |
| xmode Context | shows source code around an error |
| xmode Verbose | alo shows the arguments going into the function where the error occured |
| pdb | Toggls automatic pdb. Upon hitting an error, you are dropped into the Python debugger. See {ln: Python debugger} for details. |
| run -d scriptName | starts the debugger from the beginning of the script |
| debug | go into the debugger right away. |
IPython from any script
IPython can be embedded in a script. Wherever the command ipshell() occurs in your code, an IPython shell will pop up, giving you full access to everything in the namespace of the script. This is extremely useful if you want to add interactive functionality to a program, or need to check on some variables without using the debugger.
from IPython.Shell import IPShellEmbed
ipshell = IPShellEmbed()
ipshell() # add this wherever you would like to open an IPython window
Each ipshell() will open up a new shell. You have to close the newly opened shell using exit() or Exit before the script will continue.
Checking performance of your code
| time sum(range(10000000)) | time the summing of the list of numbers 1 through ten million and print how long it took |
| timeit sum(range(1000)) | automatically figures out if it should try a couple times to get an accurate estimate for commands that take very little time. Prints average time. |
| prun go() | runs the profiler on the function, go(). The output from the profiler shows how long it took for each part of the script to run. prun works on expressions, not files. |
| run -p scriptname | runs the profiler on the script, "c">scriptname. run -p works on files, not statements. |
0 Responses to “Debug and optimize your code in IPython”