What are good options for debugging urwid applications? - python

My current makeshift approach is logging to a textfile, but that isn't very interactive. I've tried using pdb, but that doesn't seem to get along with urwid, pdb doesn't take any input once it hits a breakpoint.

A couple of practices down the line... Debugging urwid is strange and not really well possible in the classical sense, most of the time after rendering the canvas you can't really check things anymore.
What helped me:
Routing errors into a file. If you get exceptions and want to understand what, where and how, nice implementation is given here: https://stackoverflow.com/a/12877023/5058041
Really try to understand what your modules are and how you want to achieve things. Reading the documentation for the n+1-time is a good idea.
Look at the implementation of the widgets you use. Often they have some more information.
I know that doesn't really count as debugging, but it helped me a lot in finding errors or strange behavior.

One thing I've found myself doing is to add a text widget just to display debugging messages.
I haven't built many complicated apps (a solitaire game was the biggest app i wrote with it), so this approach was good enough.
In some specific cases, you might still be able to get away using PUDB -- but since it's also using Urwid, it will steal the output from the app. In practice, after you go from your app to pudb (maybe from a pudb.set_trace() breakpoint added to your code), then you won't be able to get back to your app.
For more complex applications it might be interesting to build a "debug mode", or maybe you could try using remote pudb? Haven't tried that yet, but it looks useful. =)

just in case anyone's searching for a better answer, I can report that VSCode's Python debugger debugpy is excellent for debugging urwid applications (and for debugging Python generally.) Your debugger is entirely separate from the console and doesn't interfere with drawing.

Related

How to use pdb effectively to debug Django?

I have been recommended to use pdb to understand and debug Django applications. Though I haven't found it very effective and want to learn how to avail maximum gain. To debug, below is how I generally proceed:
I set breakpoint at most suspicious code section or at a point where control is going and then proceed with next or continue. As method completes I found myself in Django source code with no hint how to proceed to next code section written by developer. Previously I have worked on big C++ application and gdb was really helpful to understand control flow and debug. I want to achieve same thing with pdb for Django project at hand and any help even apart from pdb is appreciated?

Free Python programming environement with autocompletion

I've looked at most of the IDE's out there. I've set up vim to use autocompletion and I'm using it right now. However, I can't seem to get it to work like Visual Studio with .NET. Autocompletion seems to work only in certain cases and it only shows methods and not what parameters they take. It's pretty much unusable to me.
What I'm after is a pop-up that will show me all methods available and the parameters they take. Pretty much the feel of VS2010 when you're programming .NET.
You won't get the kind of autocompletion in a dynamic language like Python that you get in more explicitly typed languages. Consider:
def MyFunction(MyArg):
MyArg.
When you type the "." in MyArg., you expect the editor to provide a list of methods with arguments. That can't happen in Python because the editor has absolutely no way of knowing what type (or types) MyArg could possibly be. Even the Python compiler doesn't have that information when it's compiling the code. That's why, if you put MyArg.SomeNonExistentFunction() you won't get any kind of error message until runtime.
If you wrote something like:
def MyFunction:
MyObject = MyClass(SomeArg)
MyObject.
then a smart enough editor can supply a list of methods available after that final ".".
You'll find that those editors that are supplying autocomplete "sometimes" are doing so in cases similar to my second example, and not doing so in cases similar to the first. With Python, that's as good as you can get.
I've been using Eclipse with the PyDev extension for some time now. The auto-completion there is really quite impressive, I highly recommend it.
Gedit has a developer plugin which tries to do some syntax completion. For reasons already mentioned, it doesn't work very well. I found it more annoying than helpful and disabled it after a few weeks trial.
ipython's new Qt console has tab completion and you can have some tooltip sort of popups with syntax help and docstrings. See screenshot below for example..
But as most people have already pointed out, this kind of thing you are asking for is really more appropriate for less dynamic languages.

Lightweight console/IDE for Python?

I often use ipython (or the regular python shell) to test python code snippets while coding, and it's been very useful. One shortcoming of this, though, is that if I want to test a multi-line segment of code, or want to write multiple lines of code before running, it isn't very convenient to have to do it "line by line". And even going back to change some of the lines is cumbersome because you have to re-type all the code that comes after it.
I'm playing with Groovy right now and I find that it has an excellent solution to this problem: the Groovy Console. You just write all the code you want, it's just like a regular editor; and then you hit run Ctrl+R (Cmd+R actually since I'm on a Mac) and it runs everything at once. If you want to change something (e.g. if there are errors), then that's easy too -- just change it and Ctrl+R again.
Is there an equivalent of this available for python? Or do you have any recommendations on a way to achieve similar behavior? I could just create a new file, save it, and then python <filename>.py from the shell. But that's just too many steps and would be cumbersome. Eclipse may be an option, but it's too heavyweight. I'm really looking for something lightweight that I can just spin up when I want to test something and then get rid of it just as quickly.
I'd be interested to hear any ideas/suggestions!
Thanks
You might give DreamPie a try. As far as I can tell from a quick read of the groovyConsole page you linked to, DreamPie features a similar input area/output area division (they call it "code box" and "history box"). The code you execute is by default cleared from the code box - which groovyConsole apparently doesn't do - but you can easily retrieve it (Ctrl+Up), or change a preference setting to "Leave code in the code box after execution".
Have you tried using IDLE, the standard Python IDE? You'd have to save the code as <filename>.py within IDLE, but after that you can run it using F5.
The Python docs link to this intro to IDLE, which may be helpful even if it's a little outdated.
I am using emacs and its python-mode.
C-c C-c: evals the current buffer
but you can also eval region (ie selection), functions etc ...
You can even make python-mode use ipython (like I do).
See http://ipython.scipy.org/dist/ipython.el . It works nicely
Did you try PyCrust? It has excellent multi-line editing, copy/paste support.
PyCrust can be found in wxPython Docs and Demos.

WxPython differences between Windows and Linux

The tutorials I've found on WxPython all use examples from Linux, but there seem to be differences in some details.
For example, in Windows a Panel behind the widgets is mandatory to show the background properly. Additionally, some examples that look fine in the tutorials don't work in my computer.
So, do you know what important differences are there, or maybe a good tutorial that is focused on Windows?
EDIT: I just remembered this: Does anybody know why when subclassing wx.App an OnInit() method is required, rather than the more logical __init__()?
I've noticed odd peculiarities in a small GUI I wrote a while back, but it's been a long time since I tried to the specifics are a rather distant memory. Do you have some specific examples which fail? Maybe we can improve them and fix the bugs?
Have you tried the official wxPython tutorials? ...or were you after something more specific?
r.e. your edit - You should use OnInit() because you're subclassing wx.App (i.e. it's a requirement for wxWidgets rather than Python) and the wxPython implementation is wherever possible, just a wrapper for wxWidgets.
[Edit] Zetcode has a fairly lengthy tutorial on wxPython. I've not looked through it all myself, but it might be of some help?
The wxWidgets::wxApp::OnInit() documentation is fairly clear:
This must be provided by the application, and will usually create the application's main window, optionally calling wxApp::SetTopWindow. You may use OnExit to clean up anything initialized here, provided that the function returns true.
If wxWidgets didn't provide a common interface then you'd have to do different things in C++ (using a constructor) compared to Python's __init__(self,...). Using a language-independent on-initialisation allows wxWidgets ports to other languages look more alike which should be a good thing right? :-)
EDIT: I just remembered this: Does anybody know why when subclassing wx.App an OnInit() method is required, rather than the more logical __init__()?
I use OnInit() for symmetry: there's also an OnExit() method.
Edit: I may be wrong, but I don't think using OnInit() is required.
I find a number of small differences, but don't remember all of them. Here are two:
1) The layout can be slightly different, for example, causing things to not completely fit in the window in one OS when the do in the other. I haven't investigated the reasons for this, but it happens most often when I use positions rather than sizers to arrange things.
2) I have to explicitly call Refresh more in Windows. For example, if you place one panel over another, you won't see it the top panel in Windows until you call Refresh.
I general, I write apps in Linux and run them in Windows, and things work similarly enough so this is a reasonable approach, but it's rare for me when something runs perfectly straight out of the gate after an OS switch.

What are good ways to make my Python code run first time? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm getting quite a few errors in my code. Consequently, I would like to be able to minimize them at the outset or see as many errors as possible before code execution. Is this possible and if so, how can I do this?
If you're having problems with syntax, you could try an editor with syntax highlighting. Until you get the feel for a language, simple errors won't just pop out at you.
The simplest form of debugging is just to insert some print statements. A more advanced (and extensible) way to do this would be to use the logging module from the std lib.
The interactive interpreter is a wonderful tool for working with python code, and IPython is a great improvement over the built-in REPL (Read Eval Print Loop).
If you actually want to step through your code, the python debugger is called pdb, which can be called from the command line, or embedded in your code.
If you're used to a fully integrated IDE, I would recommend using Eclipse with pydev, and PyCharm has a great commercial offering, with autocomplete, quick access to docs, and numerous shortcuts, among many other interesting features.
Here is some techniques to facilitate debugging in Python:
use interactive shell e.g., ipython. Python is a dynamic language you can explore your code as you type. The shell is running in the second window in my editor at all times.
copy-paste from the shell into docstrings a code that illustrates a dominant usage and corner cases of the function (class, module). doctest.testmod() placed in a if __name__=="__main__" section allows to test all docstrings in the module. doctest can be easily integrated with unittest.
use assert for stuff that can never happen.
print() can solve many debugging problems; logging module is suitable for long-living python processes.
write tests (not necessarily before your code), run them often (automatically or with one keystroke at most); nose provides extended test discovery and running features for unittest.
run pylint occasionally.
At this point there is a little use for a formal python debugger.
Winpdb is an external multi-platform GPL'ed GUI python debugger if you need one.
All the really cool stuff is easily demonstrated in the interactive interpreter. I think this might be the "gold standard" for good design:
Can you exercise your class interactively?
If you can do stuff interactively, then you can write unittests and doctests with confidence that it's testable, simple, reliable.
And, more important, you can explore it interactively. There's nothing better than the instant gratification that comes from typing code and seeing exactly what happens.
The compiled language habits (write a bunch of stuff, debug a bunch of stuff, test a bunch of stuff) can be left behind. Instead, you can write a little bit of stuff, explore it, write a formal test and then attach your little bit of stuff to your growing final project.
You still do overall design. But you don't squander time writing code that may or may not work. In Python you write code that works. If you're not sure, you play with it interactively until you're sure. Then you write code that works.
I am new to python, and have been trying several different debuggers. Here are the options I've come across so far:
Eclipse with Pydev - If you're already using eclipse, this is probably the way to go. The debugger works well, and is pretty featureful.
Komodo IDE - A light-weight python IDE. Basically a text editor + a debugger. It was really easy to figure out and be productive with immediately.
WinPDB - Trying this one next. Looks very featureful, and I get to use whichever editor I choose.
PDB - Haven't tried yet since I've read about how WinPDB is a better alternative.
Ipython with %run command - I've used IPython, but not as a debugger like this. I need to try this out. (Thanks for the tip, EOL)
Eric IDE - Also on the list to try.
Old-school print, assert statements - Simple, useful, but not a full solution.
Memory debugging - To debug memory problems, I've come across a few tools:
objgraph - Will generate png's of reference graphs. Neat. There's other functionality as well, like: import objgraph;print(objgraph.show_most_common_types(limit=10)) will print the top 10 most common types in memory.
gc module - Interact directly with the garbage collector.
heapy - Heap analyzer. For example: from guppy import hpy; hp = hpy(); print(hp.heap()) will print the most common types, their memory usage, etc.
This is a very incomplete list, but hopefully it's a good start.
Python provides a debugger which allows you to step through your code, inspect variables and manipulate them. Refer to http://pythonconquerstheuniverse.wordpress.com/category/python-debugger/ which can take you over the steps...
Also check the python standard library reference for pdb
http://www.python.org/doc/2.5.2/lib/module-pdb.html
Test early and test often.
This doesn't necessarily mean to jump into the test driven design pool head first (though that's not such a bad idea). It just means, test your objects and methods as soon as you have something that works. Don't wait until you have a huge pile of code before doing testing.
Invest some time in learning a testing framework. If it's trivial for you to type in a test case you'll more likely do it. If you don't have any sort of framework testing can be a pain so you'll avoid it. So, establish some good habits early on and you'll have fewer problems down the road.
More often than not, I just use a bunch of print statements.
page = grabpage(url)
print "Page content:", page
print "page type():", type(page)
It's sometimes useful to do something like:
debug = True
if debug: print "page content", page
..with this you can quickly disable all your debugging print statements by changing the debug variable to False.
While print-debugging will get you very far in most cases, sometimes it's difficult to debug things like loops, or a series of if/else/try/except/etc. For this a debugger that allows stepping though your code, and setting break-points is useful.
pdb is included with Python. Here is a good simple tutorial on it. You can even do things like changing variables during run-time (which the tutorial covers). A longer tutorial can be found here
There is a very nice GUI equivalent pdb - Winpdb
Basically you run winpdb myscript --arg 4 -b 4 then it loads the command in a terminal, shows you your code on the left, with the current, a list of local/global variables (and their values) and the current call-stack.
Then you can step though the code by clicking the Step (or F6). F5 runs the code. If you click next to the line numbers, it sets a break point, where the code will automatically step (when you press run).
I find it far easier to use, and it has lots of addition enhancements (like remote debugging, so you can run the backend portion (rpdb2) in the to-be-debugged application, and connect Winpdb to it (encrypted). It also has support for threading and other useful things not in PDB. You have access to a pdb-like console too.
I set up Python to automatically start the debugger when there's an uncaught exception, using this trick. That way, you can easily examine the state of the program without too much logging code. (Plus, to send me a Growl notification.)
Oh, and this way you can just create a break point in the code by adding
if answer == 42:
1/0
Using assert statement liberally.
Identifing errors before execution is the domain of static checking/analysis. I've had good luck using PyChecker for basic static checking of Python code.
The pycheesecake site has a very good summary of testing tools for Python.
The PyDev plugin for eclipse is my tool of choice. It recognizes simple syntax mistakes and indentation errors and underlines the error with a red line. It has a powerful debugger and even has a plugin called PyLint which warns you about dangerous code.
Edit:
It also has a user friendly stack trace on runtime errors, partial auto complete and some other nifty features.
Edit again:
I didn't notice that pydev was mentioned in the top post. I hope I brought something else to the table.
python -m pdb yourcode.py should do it.
Alternatively you can "import pdb" in your code and use pdb.set_trace() to set break points.
Refer the manual for more info: http://www.python.org/doc/2.5.2/lib/module-pdb.html
There is very nice GUI debugger for Python called Winpdb. Try it out.Built on wxWidgets library and multiplatform.
For a most integrated experience you can use full blown IDE like PyCharm:
http://blog.jetbrains.com/pycharm/files/2011/05/template-debug2.png
Eric4 IDE also has a great built-in debugger.
The IPython Python shell has a %pdb command that automatically invokes the debugger in case of problem. You can then inspect variables, step through the code, etc.
You can run your programs from IPython with the %run command.
More generally, as as been noted in some other answers, a good Python shell is your friend. And IPython is your best friend. :)

Categories