Lightweight console/IDE for Python? - 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.

Related

How to Run Python without a Terminal

I want to teach some students basic Python programming without having to teach them how to use the terminal. Recently, I was teaching a 2 hour intro session, and not only did teaching terminal stuff take a long time, but it also intimidated a lot of the students. I would like a solution where students wouldn't have to leave graphical user interfaces that they were comfortable with.
I also want the solution to let them execute a particular Python file (eg, not just using the interactive Python interpreter) and see the output from printing things.
Thanks!
Surely that's what IDLE is for? It's not much good as an IDE, but it does work well for exactly what you describe - opening modules and executing them, and running commands in an interactive shell.
How about this?
https://www.wakari.io/
All in the browser.
Bonus points, you introduce them to IPython as well.
Take a look at the gallery too, https://www.wakari.io/gallery
You might want to try something like this: http://repl.it/languages/python
Perhaps you want something like this:
http://learn.adafruit.com/webide/overview
When I'm not near my own PC, I use ideone.com. I like that it is a universal IDE, which for me means both C++ and Python.

checking/verifying python code

Python is a relatively new language for me and I already see some of the trouble areas of maintaining a scripting language based project. I am just wondering how the larger community , with a scenario when one has to maintain a fairly large code base written by people who are not around anymore, deals with the following situations:
Return type of a function/method. Assuming past developers didn't document the code very well, this is turning out to be really annoying as I am basically reading code line by line to figure out what a method/function is suppose to return.
Code refactoring: I figured a lot of code need to be moved around, edited/deleted and etc. But lot of times simple errors, which would otherwise be compile time error in other compiled languages e.g. - wrong number of arguments, wrong type of arguments, method not present and etc, only show up when you run the code and the code reaches the problematic area. Therefore, whether a re-factored code will work at all or not can only be known once you run the code thoroughly. I am using PyLint with PyDev but still I find it very lacking in this respect.
You are right, that's an issue with dynamically typed interpreted languages.
There are to important things that can help:
Good documentation
Extensive unit-testing.
They apply to other languages as well of course, but here they are especially important.
As far as I know If code is not documented at all and the author isn't around anymore it's up to you to find out what the ode actually does.
That's why people should always stick to certain guidelindes that can be enforced by stylecheckers like pep8. https://pypi.python.org/pypi/pep8
Comments and docstrings should be included in every method to avoid such situation you're describing. http://www.python.org/dev/peps/pep-0257/#what-is-a-docstring
Also unittests are very helpfull for refactoring since you can check if you broke something with the click of a button. http://docs.python.org/2/library/unittest.html
hope this helps
Others have already mentioned documentation and unit-testing as being the main tools here. I want to add a third: the Python shell. One of the huge advantages of a non-compiled language like Python is that you can easily fire up the shell, import your module, and run the code there to see what it does and what it returns.
Linked to this is the Python debugger: just put import pdb;pdb.set_trace() at any point in your code, and when you run it you will be dropped into the interactive debugger where you can inspect the current values of the variables. In fact, the pdb shell is an actual Python shell as well, so you can even change things there.

bpython-like autocomplete and parameter description in Emacs Python Mode?

I've been using bpython for a while now for all of my Python interpreting needs. It's delightful, particularly when you're using unfamiliar new libraries, or libraries with a multitude of functions. In any case, it's nice to have a bpython interpreter running alongside what I'm doing, but it'd be even better if I had both the autocomplete-like feature, and the parameter description in the manner that bpython does while I'm editing code in Emacs. Am I completely crazy? Does anyone have an idea on how to do this?
Thanks,
Bradley Powers
You're not completely crazy.
python-mode can integrate with eldoc-mode to display the arg spec of the function you're calling at point. Just do M-x eldoc-mode while you're in a python file to turn it on and it should start working. It talks to an inferior python buffer to inspect the functions directly, so it should always be decently accurate. You can turn it on automatically for all new python-mode buffers with (add-hook 'python-mode-hook '(lambda () (eldoc-mode 1)) t) in your emacs startup file. Now, at this point I have to say that I don't do any regular python programming, and that when I tried it just now it didn't work. I spent a few minutes poking around in the source code and everything seems to be in place, but the code that it runs in the inferior process is just returning an empty string. Perhaps it's just my setup, or perhaps I'm reading the wrong source files; it's hard to say.
Emacs provides several different types of expansion/autocompletion. By default you have access to dabbrev-expand by hitting M-/. This is a fairly simple form of completion; it's just meant to work on any old file you happen to edit. More sophisticated is hippie-expand, but even that doesn't do anything python-specific. The documentation says that it can integrate with hippie-expand for exact completions, but this might be a lie; I couldn't figure out how it works. A little poking around shows several related solutions for this, all of which seem to rely on pymacs. If I were going to do a lot of python programming and didn't already have a fairly complicated emacs set up, I'd probably start by installing emacs-for-python. It looks to be a pretty complete setup, and even claims to have live warning/error detection.
In the spirit of helping others to help themselves, I'd like to point out how I came upon all of this information. My first step was to open a file in python-mode. I didn't actually have any python code available, so I just went to my scratch buffer and made it a python buffer (M-x python-mode). Then I asked for help about this strange new mode (C-h m) to see what it could do. It's author has kindly put a brief summary of what the mode can do which mentions eldoc-mode, Imenu, outline-mode, hippie-expand, rlcompleter, abbrev tables, and a bunch of other things. From there I started looking at the source code. For instance, to integrate with eldoc-mode, it defines a function called python-eldoc-function and gives that to the eldoc module for use in python buffers. Reading that code shows me how it interacts with the inferior buffer, etc.
I hope some of this helps.

What's the closest thing to SLIME for python ? / What's the best way to use python from EMACS?

I'm trying to write some python, and I'm used to the lispy way of doing things, a REPL in EMACS and the ability to send arbitrary code snippets to the REPL. I like this way of developing code, and python's built-in IDLE seems to do it pretty well. However I do like EMACS as an editor.
What's the best thing analogous to SLIME for Python?
So far:
It seems that the trick is to open a python file, and then to use 'Start Interpreter' from the Python menu, after which you get an Inferior Python buffer. You can then use C-c C-c to load the whole buffer you're editing into the 'REPL', and use normal copy and paste to put snippets into the REPL.
This works as far as it goes. Is there any way to say 'reevaluate the big thing that the cursor is in now and display the answer', or 'reevaluate the thing the cursor is just at the end of and display the answer', like M-C-x and C-x-e in SLIME?
And it all seems to work better if you use the python-mode.el from Bozhidar's answer
There is ipython.el which you can use for some extended functionality over the vanilla python-mode. Ropemacs provides a few extra completion and refactoring related options that might help you. This is discussed here. However, I don't expect you're going to get anything close to SLIME.
I think the new python.el is a much better idea. It's under active development, it can spawn a python shell and send function definitions, buffers and files to it. It also has better than average re-indent support. It's rumoured that in Emacs 24 it might become the default python mode in Emacs.
python-mode is the default mode for editing Python in emacs. It includes commands for evaluating the buffer and running an inferior interpreter instance.

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