An Introduction to Python
If you've been programming on a Linux system, you may be coding in C or C++. If you're a systems administrator, you may be programming in perl, Tcl, awk, or one of the various (sh/csh/tsh/bash) shell scripting languages. Maybe you wrote a script to do a particular job, but now find that it doesn't scale up very well. You might be writing C applications, but now wish you didn't have to be bogged down in the low-level details. Or you may simply be intrigued by the possibility of doing high-level, object-oriented programming in a friendly, interpreted environment.
If any of the above applies to your situation, you may be interested in Python. Python is a powerful language for the rapid development of applications. The interpreter is easily extensible, and you may embed your favorite C code as a compiled extension module.
Python is not one of the research languages which seem to get promoted solely for pedagogical reasons. It is possible to do useful coding almost immediately. Python seems to encourage object-oriented programming by clearing the paths, rather than erecting parapets.
To execute the standard hello program, enter the following at the command line:
$ python Python 1.2 (Jun 3, 1995) [GCC 2.6.3] Copyright 1991-1995 Sitchting Mathematisch Centrum, Amsterdam >> print "hello, bruce" hello, bruce >> [CONTROL]-D
Most Python programs, though developed incrementally, are executed as a normal script. The next program illustrates some extensions to the original. The new version will identify who you are based on your user account in /etc/passwd.
1 #!/usr/local/bin/python 2 3 import posix 4 import string 5 6 uid = `posix.getuid()` 7 passwd = open(`/etc/passwd') 8 for line in passwd.readlines(): 9 rec = string.splitfields(line, `:') 10 if rec[2] == uid: 11 print `hello', rec[0], 12 print `mind if we call you bruce?' 13 break 14 else: 15 print "I can't find you in /etc/passwd"
A line-by-line explanation of the program is as follows:
1 --- Command interpreter to invoke
3-4 --- Import two standard Python modules, posix and regsub.
6 --- Get the user id using the posix module. The enclosing backticks (`) tell Python to assign this value as a string.
7 --- Open the /etc/passwd file in read mode.
8 --- Start a for loop, reading in all the lines of /etc/passwd. Compound statements, such as conditionals, have headers starting with a keyword (if, while, for, try) and end with a colon.
9 --- Each line in /etc/passwd is read and split into array rec[] based on a colon : boundary, using string.splitfields()
10 --- If rec[2] from /etc/passwd matches our call to posix.getuid(), we have identified the user. The first 3 fields of /etc/passwd are: rec[0] = name, rec[1] = password, and rec[2] = uid.
11-12 --- Print the user's account name to stdout. The trailing comma avoids the newline after the output.
13 --- Break the for loop.
14-15 --- Print message if we can't locate the user in /etc/passwd.
The observant reader will note that the control statements lack any form of BEGIN/END keywords or matching braces. This is because the indentation defines the way statements are grouped. Not only does this eliminate the need for braces, but it enforces a readable coding style. No doubt this design feature will turn off a few potential Python hackers, but in practice, it is useful. I can think of numerous times I've spent tracking bugs in C resulting from misinterpreting code that looked like any of these fragments, usually deeply nested:
if (n == 0)
x++;
y--;
z++;
if (m == n || (n != o && o == q)) { j++; }
k++;
q = 0;
while (y--)
*ptr++;
if (m == n) {
x++;
}
A coding style enforced in the language definition would have saved me much frustration. Python code written by another programmer is usually very readable.
You might object that we did a lot of work in the program above just to demonstrate Python language features. A better method would be to use the pwd module from the standard Python library:
print `hello', pwd.getpwuid(posix.getuid())[0]
This points out another nicety about Python that is critical for any new language's success: the robustness of its library. As mentioned earlier, you may extend Python by adding a compiled extension module to your personal library, but in most cases you don't have to.
Take the ftplib module for instance. If you wanted to write a Python script to automatically download the latest FAQ, you can simply use ftplib in the following example:
#!/usr/local/bin/python from ftplib import FTP ftp = FTP(`ftp.python.org') # connect to host ftp.login() # login anonymous ftp.cwd(`pub/python/doc') # change directory ftp.retrlines(`LIST') # list python/doc F = open(`python.FAQ', `w') # file: python.FAQ ftp.retrbinary(`RETR FAQ', F.write, 1024) ftp.quit()
Python has numerous features which make programming fun and restore your perspective of the design objectives. The language encourages you to explore its features by writing experimental functions during program development. Several notable Python features:
Automatic memory management. No malloc/free or new/delete is necessary—when objects become unreachable they are garbage-collected.
Support for manipulating lists, tuples, and arrays
Associative arrays, referred to as “Dictionaries” in Python
Modules to encourage reusability. Python comes with a large set of standard modules that may be used as the basis for learning to program in Python.
Exception handling
Classes
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Designing Electronics with Linux | May 22, 2013 |
| Dynamic DNS—an Object Lesson in Problem Solving | May 21, 2013 |
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
- RSS Feeds
- Dynamic DNS—an Object Lesson in Problem Solving
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Designing Electronics with Linux
- Using Salt Stack and Vagrant for Drupal Development
- New Products
- A Topic for Discussion - Open Source Feature-Richness?
- Drupal Is a Framework: Why Everyone Needs to Understand This
- Validate an E-Mail Address with PHP, the Right Way
- What's the tweeting protocol?
Enter to Win an Adafruit Pi Cobbler Breakout Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Pi Cobbler Breakout Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- 5-21-13, Prototyping Pi Plate Kit: Philip Kirby
- Next winner announced on 5-27-13!
Free Webinar: Hadoop
How to Build an Optimal Hadoop Cluster to Store and Maintain Unlimited Amounts of Data Using Microservers
Realizing the promise of Apache® Hadoop® requires the effective deployment of compute, memory, storage and networking to achieve optimal results. With its flexibility and multitude of options, it is easy to over or under provision the server infrastructure, resulting in poor performance and high TCO. Join us for an in depth, technical discussion with industry experts from leading Hadoop and server companies who will provide insights into the key considerations for designing and deploying an optimal Hadoop cluster.
Some of key questions to be discussed are:
- What is the “typical” Hadoop cluster and what should be installed on the different machine types?
- Why should you consider the typical workload patterns when making your hardware decisions?
- Are all microservers created equal for Hadoop deployments?
- How do I plan for expansion if I require more compute, memory, storage or networking?




6 hours 13 min ago
10 hours 40 min ago
14 hours 16 min ago
14 hours 48 min ago
17 hours 12 min ago
17 hours 15 min ago
17 hours 16 min ago
21 hours 41 min ago
23 hours 32 min ago
1 day 4 hours ago