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
Today’s modular x86 servers are compute-centric, designed as a least common denominator to support a wide range of IT workloads. Those generic, virtualized IT workloads have much different resource optimization requirements than hyperscale and cloud applications. They have resulted in a “one size fits all” enterprise IT architecture that is not optimized for a specific set of IT workloads, and especially not emerging hyperscale workloads, such as web applications, big data, and object storage. In this report, you will learn how shifting the focus from traditional compute-centric IT architectures to an innovative disaggregated fabric-based architecture can optimize and scale your data center.
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
| 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 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
| Trying to Tame the Tablet | May 08, 2013 |
| Dart: a New Web Programming Experience | May 07, 2013 |
- RSS Feeds
- New Products
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Drupal Is a Framework: Why Everyone Needs to Understand This
- Home, My Backup Data Center
- A Topic for Discussion - Open Source Feature-Richness?
- What's the tweeting protocol?
- Dart: a New Web Programming Experience
- Developer Poll
- May 2013 Issue of Linux Journal: Raspberry Pi
Enter to Win an Adafruit Prototyping Pi Plate 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 Prototyping Pi Plate 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
- Next winner announced on 5-21-13!
Free Webinar: Linux Backup and Recovery
Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.
In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.




1 hour 2 min ago
3 hours 35 min ago
4 hours 52 min ago
5 hours 27 min ago
5 hours 49 min ago
10 hours 38 min ago
11 hours 25 min ago
12 hours 59 min ago
14 hours 35 min ago
16 hours 33 min ago