It may seem like Python is just another scripting language, but know that when you are using Linux, the chances are there is some Python code working backstage helping you. Among other things, this article looks into the versatile nature of Python and its many uses…
Every now and then you will realise that compiled programming is just not cutting it for you and you want to get your work done. In fact, at these times you just want to be freed from all the boundaries that compiled languages put in front of you, like the processor dependency, OS dependency, static typing and altogether the complexity of a compiled language. Python is a good answer for this type of situation.
Mostly seen as a scripting language for system administrators, it is actually capable of doing almost everything and beyond the limitations of regular programming languages. Python started its life as a time-saver programming language. Python’s inventor Guido van Rossum started the project with a set of philosophical rules which drives Python even today.
These philosophical rules led to some of the primary reasons behind the popularity of Python, such as better software quality, component integration, extensibility, cross-platform support and developer productivity.
In this article we will look into the diverse range of applications of Python. We will look into the following categories:
1. System administration
2. Desktop (GUI) application development
3. Web development
4. Application scripting and component integration
5. Game development
System Administration
A system administrator’s job is not an easy one. They often need to do things like managing users, disk quotas, processes, devices and so on. Doing these tasks again and again on a large scale can cause a lot of stress and even result in premature hair loss! No kidding. Read the book Mastering Windows Server 2000 Registry for more details.
Python can be of great help to system administrators by automating a lot of administration tasks. In this section we will look at some sample Python scripts that will give you an idea about how to perform system administration tasks using Python. It is important to note here that for most of the tasks we will be using Python’s built-in modules only.
Checking for root user
Some commands only work in root mode. So it will be very helpful if we can check whether the current user is root or not. The following script performs this job. Root is associated with User ID (UID) 0. Hence we are checking for that value to determine who is a root user.
Code for: checkroot.py
@description: Check for root user import os if os.getuid() == 0: print(“You are a root user !”) else: print (“You are a regular guy .”) @ @output kunal@Dell-Work:~/python$ python checkroot.py You are a regular guy . kunal@Dell-Work:~/python$ sudo python checkroot.py You are a root user ! @
Process information
Occasionally a system administrator might need to look into the details of a process that is causing problems. In order to do this we will make use of the commands module which contains wrapper functions for os.popen() which take a system command as a string and return any output generated by the command and, optionally, the exit status. In this case we are running the ps command and then formatting the output of ps according to our needs. This will only work on UNIX systems as we are making use of ps.
Code for:psinfo.py
@Description: Process Information
import commands, os, string myps = raw_input(“Enter the Process Name: “) result = commands.getoutput(“ps -ef|grep “ + myps) psinfo = string.split(result) print “\n\ Terminal:\t\t”, psinfo[5], “\n\ Owner:\t\t\t”, psinfo[0], “\n\ Process ID:\t\t”, psinfo[1], “\n\ Parent process ID:\t”, psinfo[2], “\n\ Time started:\t\t”, psinfo[4] @ @output:
kunal@Dell-Work:~/python$ python psinfo.py
Enter the Process Name: konsole
Terminal: pts/0
Owner: kunal
Process ID: 1977
Parent process ID: 1
Time started: 14:30
@
File search
File search is essential to any system administration task. In this section we will build a Python file search script which will search for files based on the given pattern(s) and will also return the file permissions. Like the earlier program, this script will also make use of the commands module to issue the UNIX command ‘find’. We will also make use of a Python module called ‘stat’ to fetch the permissions information.
Code for: filesearch.py
@description: file pattern search script import stat, sys, os, string, commands pattern = raw_input(“Enter the file pattern to search for:\n”) command = “find “ + pattern output = commands.getoutput(command) findResults = string.split(output, “\n”) print “Found Files:” print output print “================================” for file in findResults: mode=stat.S_IMODE(os.lstat(file)[stat.ST_MODE]) print “\nPermissions for file “, file, “:” for level in “USR”, “GRP”, “OTH”: for perm in “R”, “W”, “X”: if mode & getattr(stat,”S_I”+perm+level): print level, “ has “, perm, “ permission” else: print level, “ does NOT have “, perm, “ permission” @code ends @output
kunaldeo$ python filesearch.py
Enter the file pattern to search for:
*.py
Found Files:
filesearch.py
py.py
Permissions for filesearch.py
USR has R permission USR has W permission USR does NOT have X permission GRP has R permission GRP does NOT have W permission GRP does NOT have X permission OTH has R permission OTH does NOT have W permission OTH does NOT have X permission
Permissions for py.py
USR has R permission USR has W permission USR does NOT have X permission GRP has R permission GRP does NOT have W permission GRP does NOT have X permission OTH has R permission OTH does NOT have W permission OTH does NOT have X permission
So now you have an idea of how to use Python in system administration tasks. The following is a list of Python modules that may be of interest to system administrators…
commands: Utility functions for running external commands.
stat: Utilities for interpreting the results of os.stat(), os.lstat() and os.fstat() – in other words, it helps process the permissions.
sys: Access system-specific parameters and functions.
os: Functions to access operations on pathnames.
string: Functions for common string operations.
tty: Utility functions that perform common terminal control operations.
syslog: An interface to the UNIX syslog library routines.
Desktop application development
Since the early days of Python, it has had robust support for Tcl/Tk-based support GUI applications called TkInter. Back then it was considered as the de facto standard for GUI app development. Linux oldies will remember that the first interface for kernel configuration was originally written in Tcl/Tk. Starting from the 2.6 series, the kernel configuration interface was available in either Qt or GTK. Since then the world has moved on. Most of the GUI application development is done using GTK, Qt or wxWindows. Python supports most of the current-generation GUI toolkit in the form of PyGTK, PyQt and wxPython.
PyGTK
PyGTK is a library that lets developers write GUI applications using Python and the GTK+ GUI toolkit. As most of you will know, GTK is the backbone of the GNOME desktop and is used for almost all GNOME desktop applications. PyGTK adopts a more liberal licence (LGPL) which makes it the number one choice for commercial software vendors who are often not comfortable with sharing the source code of their application. PyGTK is also fully compliant with the Glade RAD (Rapid Application Development) tool and can be used for rapid application prototyping.
It is important to note that when we use the PyGTK program to build a GUI application, while porting the application to some other platform you will only need the platform-specific binary for PyGTK library and not the main program source code. As Python codes are not interpreted, the same code will run without any modification.
PyGTK leverages the complete technology stack of GTK. GTK technology stack consists of GObject, ATK, GTK, Pango, Cairo and Glade (optional). GObject is a base class providing the common attributes and functions for PyGTK classes. ATK is the accessibility toolkit, which provides tools that help physically challenged people work with computers. GTK is the user interface module. The Pango is a library which is used to work with text and internationalisation. Cairo is a library for creating 2D vector graphics. Finally, Glade is used to build GUI interfaces from XML descriptions.
Hello PyGTK
To get a feel of PyGTK, let’s build a Hello World application using PyGTK. Before running the code, make sure that you have installed the PyGTK package.
Code for:hellopygtk.py
import pygtk import gtk class HelloWorld: # This is a callback function. The data arguments are ignored # in this example. More on callbacks below. def hello(self, widget, data=None): print “Hello World” def delete_event(self, widget, event, data=None): # If you return FALSE in the “delete_event” signal handler, # GTK will emit the “destroy” signal. Returning TRUE means # you don’t want the window to be destroyed. # This is useful for popping up ‘are you sure you want to quit?’ # type dialogs. print “delete event occurred” # Change FALSE to TRUE and the main window will not be destroyed # with a “delete_event”. return False def destroy(self, widget, data=None): print “destroy signal occurred” gtk.main_quit() def __init__(self): # create a new window self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) # When the window is given the “delete_event” signal (this is given # by the window manager, usually by the “close” option, or on the # titlebar), we ask it to call the delete_event () function # as defined above. The data passed to the callback # function is NULL and is ignored in the callback function. self.window.connect(“delete_event”, self.delete_event) # Here we connect the “destroy” event to a signal handler. # This event occurs when we call gtk_widget_destroy() on the window, # or if we return FALSE in the “delete_event” callback. self.window.connect(“destroy”, self.destroy) # Sets the border width of the window. self.window.set_border_width(10) # Creates a new button with the label “Hello World”. self.button = gtk.Button(“Hello World”) # When the button receives the “clicked” signal, it will call the # function hello() passing it None as its argument. The hello() # function is defined above. self.button.connect(“clicked”, self.hello, None) # This will cause the window to be destroyed by calling # gtk_widget_destroy(window) when “clicked”. Again, the destroy # signal could come from here, or the window manager. self.button.connect_object(“clicked”, gtk.Widget.destroy, self.window) # This packs the button into the window (a GTK container). self.window.add(self.button) # The final step is to display this newly created widget. self.button.show() # and the window self.window.show() def main(self): # All PyGTK applications must have a gtk.main(). Control ends here # and waits for an event to occur (like a key press or mouse event). gtk.main() # If the program is run directly or passed as an argument to the python # interpreter then create a HelloWorld instance and show it if __name__ == “__main__”: hello = HelloWorld() hello.main()
Web application development
Python has strong support for both ends of the web, ie server side and client side. Let’s look at some of the important web offerings created in Python:
TurboGears 2: TurboGears is a Python web application framework consisting of several WSGI components such as Pylons, SQLAlchemy, Genshi and Repoze.
Django: Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. Django has already been covered in this magazine – please see issue 86 of Linux User & Developer to read more about Django and how to use it to develop apps. There are also various client-side frameworks available in Python which we will cover in the coming issues.
TurboGears 2 is built around various WSGI (Web Server Gateway Interface) components. WSGI is a Python technology which defines a simple and universal interface between web servers and web applications or frameworks for the Python programming language. Together, these WSGI components form an MVC (model-view-controller) compatible architecture. TurboGears 2 uses the following WSGI components:
SQLAlchemy (model): SQLAlchemy is an open source SQL toolkit and object-relational mapper for the Python programming language, released under the MIT License. In TurboGears 2 it handles the table structures of the user’s database and enables the linking of them to Python objects that the user’s controller can interact with.
Genshi (view): Genshi acts as the template engine for TurboGears 2. It uses XML-based vocabularies written in Python. Genshi is used to easily insert generated output into XML-based languages, usually HTML, and reuse elements between documents.
Pylons (controller): Pylons is a WSGI-compliant web framework. In TurboGears 2 it acts as the brain of the framework. It handles all of the user’s back-end logic and connects to the user’s web server to offer up data to the web.
Repoze: This was originally conceived as an effort to bring WSGI to the Zope framework. Under TurboGears 2, Repoze looks after the security of web applications. Its specific modules, Repoze.who and Repoze.what, are used to handle authentication and authorization respectively.
Tosca Widgets: ToscaWidgets is a framework for building reusable web components. It is the primary widget library for creating forms and complex GUIs. Tosca by default will generate simple HTML forms, but can also be used as middleware to connect to more advanced JavaScript widgets and toolkits.