Python on Linux


Ubuntu comes with Python installed by default, as do many other versions of Linux and UNIXeven Mac OS X comes with Python preinstalled. Part of this is due to convenience because it is such a popular scripting language and it saves having to install it later if the user wants to run a script.

The Python binary is installed into /usr/bin/python; if you run that, you enter the Python interactive interpreter where you can type commands and have them executed immediately. Although PHP also has an interactive mode (use php a to activate it), it is neither as powerful nor as flexible as Python's.

As with Perl, PHP, and other scripting languages, you can also execute Python scripts by adding a shebang line (#!) to the start of your scripts that point to /usr/bin/python and then setting the file to be executable.

The third and final way to run Python scripts is through mod_python, which you can install through synaptic.

For the purposes of this introduction, we use the interactive Python interpreter because it provides immediate feedback on commands as you type them.

Getting Interactive

We will be using the interactive interpreter for this chapter, so it is essential that you are comfortable using it. To get started, open a terminal and run the command python. You should see this:

[paul@caitlin ~]$ python Python 2.4.3 (#2, Apr 27 2006, 14:43:58) [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 


The >>> is where you type your input, and you can set and get a variable like this:

>>> python = 'great' >>> python 'great' >>> 


On line one, the variable python is set to the text great, and on line two that value is read back from the variable simply by typing the name of the variable you want to read. Line three shows Python printing the variable; on line four you are back at the prompt to type more commands. Python remembers all the variables you use while in the interactive interpreter, which means you can set a variable to be the value of another variable.

When you are done, press Ctrl+D to exit. At this point, all your variables and commands are forgotten by the interpreter, which is why complex Python programs are always saved in scripts!



Ubuntu Unleashed
Ubuntu Unleashed 2011 Edition: Covering 10.10 and 11.04 (6th Edition)
ISBN: 0672333449
EAN: 2147483647
Year: 2006
Pages: 318

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net