With that out of the way, let's get down to actually doing something with Python. I'm assuming here that you've already got Python up and running on your system; if you haven't, now is a good time to visit http://www.python.org/ and download a version for your platform (installation instructions are included with each distribution, and you might also want to download a copy of the Python documentation and function reference.) The examples in this series will assume Python on Linux, although you're free to use it on the platform of your choice. If you're on a UNIX system, a quick way to check whether Python is already present on the system is with the UNIX "which" command. Try typing this in your UNIX shell: If Perl is available, the program should return the full path to the Python binary, usually or There are two primary methods to run Python code - via the command line, or via a script. The command line interpreter allows you to type in Python code line by line, and executes it immediately; this is a great way to see the result of a particular statement or set of statements. You can start up the interpreter by typing in the full path to the Python binary at any command prompt. Once the interpreter starts up, you'll see a brief copyright notice and some version information, followed by a ">>>" - this indicates that the interpreter is ready and willing to receive your commands. Here's a brief example of what this might look like: You can exit the interpreter with a Ctrl-D. The disadvantage of the command line interpreter is that your code is lost once you exit it. Therefore, Python also allows you to save your code to a text file, and run this code as a script from the command line...as the following example demonstrates.
Python scripts and modules (explained later) typically end in a .py file extension. In the example above, I've specified the name of the script to run as a parameter on the command line. If you're on a UNIX system, you have the additional option of directly running the script by name, by adding a line specifying the location of the command interpreter at the top of the script file. This technique should be familiar to anyone who's programmed in Perl or bash. Note that the script file must have executable privileges - you can accomplish this with the "chmod" command. I'll be using both these techniques to demonstrate code snippets over the course of this tutorial.
blog comments powered by Disqus |