Running Python Programs
Answering the question "How do I run Python programs?" is the obvious first step in learning how to use and program python, but often people do not spend enough time thinking about this.
You know that python does not need compilation so running python should be very easy, and it is, but what is the best way to do it? Let's see what are the options:
- The classical approach of writing the script in a file and executing from the command line with some parameters
- Run interactively and loading scripts from files if necessary using the execfile or import commands
- Run python as a sub-process of a fully featured editor and freely mix writing scripts and interactive use
This is a very straightforward of running python. If you have a scripts called hello.py:
# This is hello.py print "Hello!"
it can be run very simply as:
The main drawback of this way of working is that the user can not easily access introspection features of Python. But it does have some notable advantages:
- All of the code is always stored in files, so less chance of typos, lost code, how did this happen moments.
- Scripts can easily chained from the command line and used from non-python environments.
- Encourages simple interfaces with the user
Hints for making the best of this approach is described on this page.
The simplest way of running python interactively is simply to call python without any command line arguments. The python interpreter will then start and simply wait for commands to be typed in by the user. For example:
python Python 2.5.1 (r251:54863, Mar 7 2008, 04:10:12) [GCC 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print "Hello!" Hello! >>>
If you are going to use this approach extensively, it is probably best to do it trough a specialised interface layer like IPython.
Mixed Scripting and Interaction
This is my preferred way of running and developing Python programs. It has the following advantages:
- It encourages writing code rather than typing throwaway command lines.
- It encourages writing very short, well documented, functions
- It allows immediate fine-grained unit-testing
- It greatly simplifies de-bugging
My tool of choice for doing this type interaction is emacs and it's python-mode. Besides syntax-highlighting, this mode can partner with a python sub-process. It then allows:
- Sending function or class definitions, or an arbitrary region, from the file being edited to the python interpreter
- Asking the python interpreter to reloading the file being edited as a python module
- Full command line editing facilities
- Integration with the python debugger pdb
The obligatory screen-shot: