Python is an extremely powerful and dynamic object-oriented programming language. It has similarities to scripting languages such as Perl, Scheme, and TCL, as well as other languages such as Java and C.
This chapter is designed to give you a quick glimpse into the Python language to help you understand the phrases in the subsequent chapters. It is not meant to be comprehensive; however, it should give you a feel for the language and help you understand the basics so that you can refer to the Python documentation for more information.
There are several reasons to use Python. It is one of the easier languages to pick up and start using, and yet it can be extremely powerful for larger applications. The following are just some of the good points of Python:
Portability—. Python runs on almost every operating system, including Linux/Unix, Windows, Mac, OS 2, and others.
Integration—. Python can integrate with COM, .NET, and CORBA objects. There is a Jython implementation to allow the use of Python on any Java platform. IronPython is an implementation that gives Python programmers access to the .NET libraries. Python can also contain wrapped C or C++ code.
Easy—. It is very easy to get up to speed and begin writing Python programs. The clear, readable syntax makes applications simple to create and debug.
Power—. There are new extensions being written to Python all the time for things such as database access, audio/video editing, GUI, web development, and so on.
Dynamic—. Python is one of the most flexible languages. It’s easy to get creative with code to solve design and development issues.
Open Source—. Python is an open source language, which means it can be freely used and distributed.
Python scripts are executed by a Python interpreter. On most systems, you can start the Python interpreter by executing the python
command at a console prompt. However, this can vary based on the system and development environment you have set up. This section discusses the standard methods to invoke the interpreter to execute Python statements and script files.
Invoking the interpreter without passing a script file as a parameter brings up the following prompt:
bwd-linux:/book # python Python 2.4.2 (#1, Apr 9 2006, 19:25:19) [GCC 4.1.0 (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>
The Python prompt is indicated by >>>
. If you execute a command that requires more input, a ..
. prompt will be displayed. From the interpreter prompt, you can execute individual Python statements, as follows:
>>> print "Printing a String" Printing a String
Invoking the interpreter with a script parameter, as shown next, begins execution of the script and continues until the script is finished. When the script is finished, the interpreter is no longer active.
bwd-linux:/book # python script.py Executing a Script bwd-linux:/book #
Scripts can also be executed from within the interpreter using the execfile(script)
function built in to Python. The following example shows a script being executed using the execfile()
function:
>>> execfile("script.py") Executing a Script >>>
The built-in types that you will most frequently use in Python can be grouped into the categories listed in Table 1.1 . The Type Name column shows the name that is associated with each built-in object type and can be used to determine whether an object is of a specific type using the isinstance(
object, typename
)
function, as follows:
>>> s = "A Simple String" >>> print isinstance(s, basestring) True >>> print isinstance(s, dict) False >>>
Table 1.1. Common Built-In Python Types
Type Category | Type Name | Description |
---|---|---|
None |
| None object (null object) |
Numbers |
| Boolean True or False |
| Integer | |
| Long integer | |
| Floating point | |
| Complex number | |
Set |
| Mutable set |
| Immutable set | |
Sequences |
| Character string |
| Unicode character string | |
| Base type of all strings | |
| List | |
| Tuple | |
| Immutable sequence | |
Mapping |
| Dictionary |
Files |
| File |
Callable |
| Type for all built-ins |
| Parent of all types and classes | |
| Built-in function | |
| Built-in method | |
| User-defined function | |
| Class instance | |
| Bound method | |
| Unbound method | |
Modules |
| Module |
Classes |
| Parent of all classes |
Type |
| Type for all built-ins |
The type module must be imported to use any of the type objects such as type
and types.ModuleType
.
The none type equates to a null object that has no value. The none type is the only object in Python that can be a null object. The syntax to use the none type in programs is simply None
.
The numeric types in Python are very straightforward. The bool
type has two possible values: True
or False
. The int
type internally stores whole numbers up to 32 bits. The long
type can store numbers in a range that is limited only by the available memory of the machine. The float
type uses the native double-precision to store floating-point numbers up to 64 bits. The complex
type stores values as a pair of floating-point numbers. The individual values are accessible using the z.real
and z.imag
attributes of the complex object.
The set type represents an unordered collection of unique items. There are two basic types of sets: mutable and immutable. Mutable sets can be modified (items can be added or removed). Immutable sets cannot be changed after they are created.
There are several sequence types in Python. Sequences are ordered and can be indexed by non-negative integers. Sequences are easily manipulated and can be made up of almost any Python object.
The two most common types of sequences by far are the string and list types. Chapter 2, “Manipulating Strings,” discusses creating and using the string type. Chapter 3, “Managing Data Types,” discusses the most common types of sequences and how to create and manipulate them.
The mapping type represents two collections of objects. The first collection is a set of key objects that index the second collection that contains a set of value objects. Each key object indexes a specific value object in the correlating set. The key object must be of an immutable type. The value object can be almost any Python object.
The dictionary is the only mapping type currently built in to Python. Chapter 3 discusses dictionaries and how to create and manipulate them.
The file type is a Python object that represents an open file. Objects of the file type can be used to read and write data to and from the filesystem. Chapter 4, “Managing Files,” discusses file type objects and includes some of the most common Python phrases to utilize them.
Objects of the callable type support Python’s function call operation, meaning that they can be called as a function of the program. Several objects fall into the callable type. The most common are the functions built in to the Python language, user-defined functions, classes, and method instances.
The module type represents Python modules that have been loaded by the import
statement. The import
statement creates a module type object with the same name as the Python module; then, all objects within the module are added to the __dict__
attribute of the newly created module type object.
Objects from the module can be accessed directly using the dot syntax because it is translated into a dictionary lookup. This way, you can use module.object
instead of accessing an attribute using module.__dict__(“object”)
to access objects from the module.
For example, the math module has the numeric object pi
; the following code loads the math module and accesses the pi
object:
>>> import math >>> print math.pi 3.14159265359
The Python language has many similarities to Perl, C, and Java. However, there are some definite differences between the languages. This section is designed to quickly get you up to speed on the syntax that is expected in Python.
One of the first caveats programmers encounter when learning Python is the fact that there are no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.
The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount. Both blocks in this example are fine:
if True: print "True" else: print "False"
However, the second block in this example will generate an error:
if True: print "Answer" print "True" else: print "Answer" print "False"
Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character () to denote that the line should continue. For example:
total_sum = sum_item_one + sum_item_two + sum_item_three
Statements contained within the []
, {}
, or ()
brackets do not need to use the line continuation character. For example:
week_list = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
Python accepts single (’
), double ("
) and triple (’’’
or """
) quotes to denote string literals, as long as the same type of quote starts and ends the string. The triple quotes can be used to span the string across multiple lines. For example, all the following are legal:
word = 'word' sentence = "This is a sentence. paragraph = """This is a paragraph. It is made up of multiple lines and sentences."""
Python allows for strings to be formatted using a predefined format string with a list of variables. The following is an example of using multiple format strings to display the same data:
>>>list = ["Brad", "Dayley", "Python Phrasebook", 2006] >>>letter = """ >>>Dear Mr. %s, >>>Thank you for your %s book submission. >>>You should be hearing from us in %d.""" >>>display = """ >>>Title: %s >>>Author: %s, %s >>>Date: %d""" >>>record = "%s|%s|%s|%08d" >>>print letter % (list[1], list[2], list[3]) Dear Mr. Dayley, Thank you for your Python Phrasebook book submission. You should be hearing from us in 2006. >>>print display % (list[2], list[1], list[0], list[3]) Title: Python Phrasebook Author: Dayley, Brad Date: 2006 >>>print record % (list[0], list[1], list[2], list[3]) Brad|Dayley|Python Phrasebook|00002006
Python supports the if
, else
, and elif
statements for conditional execution of code. The syntax is if expression: block
. If the expression evaluates to true execute the block of code. The following code shows an example of a simple series of if
blocks:
if x = True: print "x is True" elif y = true: print "y is True" else: print "Both are False"
Python supports the while
statement for conditional looping. The syntax is while
expression:
block
. While the expression evaluates to true, execute the block in looping fashion. The following code shows an example of a conditional while
loop:
x = 1 while x < 10: x += 1
Python also supports the for
statement for sequential looping. The syntax is for
item in sequence
: block
. Each loop item is set to the next item in the sequence, and the block of code is executed. The for
loop continues until there are no more items left in the sequence. The following code shows several different examples of sequential for
loops.
The first example uses a string as the sequence to create a list of characters in the string:
>>>word = "Python" >>>list = [] >>>for ch in word: >>> list.append(ch) >>>print list ['P', 'y', 't', 'h', 'o', 'n']
This example uses the range()
function to create a temporary sequence of integers the size of a list so the items in the list can be added to a string in order:
>>>string = "" >>>for i in range(len(list)): >>> string += list[i] >>>print string Python
This example uses the enumerate(string)
function to create a temporary sequence. The enumerate
function returns the enumeration in the form of (0, s[0]), (1, s[1]), and so on, until the end of the sequence string
, so the for
loop can assign both the i
and ch
value for each iteration to create a dictionary:
>>>dict = {} >>>for i,ch in enumerate(string): >>> dict[i] = ch >>>print dict {0: 'P', 1: 'y', 2: 't', 3: 'h', 4: 'o', 5: 'n'}
This example uses a dictionary as the sequence to display the dictionary contents:
>>>for key in dict: >>> print key, '=', dict[key] 0 = P 1 = y 2 = t 3 = h 4 = o 5 = n
The Python language provides break
to stop execution and break out of the current loop. Python also includes continue
to stop execution of the current iteration and start the next iteration of the current loop. The following example shows the use of the break
and continue
statements:
>>>word = "Pithon Phrasebook" >>>string = "" >>>for ch in word: >>> if ch == 'i': >>> string +='y' >>> continue >>> if ch == ' ': >>> break >>> string += ch >>>print string Python
An else
statement can be added after a for
or while
loop just the same as an if
statement. The else
is executed after the loop successfully completes all iterations. If a break
is encountered, then the else
statement is not executed.
There is currently no switch statement in Python. Often this is not a problem and can be handled through a series of if
-elif
-else
statements. However, there are many other ways to handle the deficiency. The following example shows how to create a simple switch statement in Python:
>>>def a(s): >>> print s >>>def switch(ch): >>> try: >>> {'1': lambda : a("one"), >>> '2': lambda : a("two"), >>> '3': lambda : a("three"), >>> 'a': lambda : a("Letter a") >>> }[ch]() >>> except KeyError: >>> a("Key not Found") >>>switch('1') one >>>switch('a') Letter a >>>switch('b') Key not Found
This section is designed to help you understand the basic concepts of objects, modules, classes, and functions in the Python language. This section assumes that you have a basic understanding of object-oriented languages and is designed to provide the information to jump into Python and begin using and creating complex modules and classes.
The Python language is tightly wrapped around the object concept. Every piece of data stored and used in the Python language is an object. Lists, strings, dictionaries, numbers, classes, files, modules, and functions are all objects.
Every object in Python has an identity, a type, and a value. The identity points to the object’s location in memory. The type describes the representation of the object to Python (see Table 1.1). The value of the object is simply the data stored inside.
The following example shows how to access the identity, type, and value of an object programmatically using the id(
object
)
, type(
object
)
, and variable name, respectively:
>>> l = [1,2,3] >>> print id(l) 9267480 >>> print type(l) <type 'list'> >>> print l [1, 2, 3]
After an object is created, the identity and type cannot be changed. If the value can be changed, it is considered a mutable object; if the value cannot be changed, it is considered an immutable object.
Some objects may also have attributes and methods. Attributes are values associated with the object. Methods are callable functions that perform an operation on the object. Attributes and methods of an object can be accessed using the following dot ‘.’ syntax:
>>> class test(object): ... def printNum(self): ... print self.num ... >>> t = test() >>> t.num = 4 >>> t.printNum() 4
The entire Python language is built up of modules. These modules are Python files that come from the core modules delivered with the Python language, modules created by third parties that extend the Python language modules that you write yourself. Large applications or libraries that incorporate several modules are typically bundled into packages. Packages allow several modules to be bundled under a single name.
Modules are loaded into a Python program using the import
statement. When a module is imported, a namespace for the module, including all objects in the source file, is created; the code in the source file is executed; and a module object with the same name as the source file is created to provide access to the namespace.
There are several different ways to import modules. The following examples illustrate some of the different methods.
Modules can be imported directly using the package or module name. Items in submodules must be accessed explicitly including the full package name.
>>> import os >>> os.path.abspath(".") 'C:\books\python'
Modules can be imported directly using the module name, but the namespace should be named something different. Items in submodules must be accessed explicitly including the full package name:
>>> import os as computer >>> computer.path.abspath(".") 'C:\books\python'
Modules can be imported using the module name within the package name. Items in submodules must be accessed explicitly including the full package name:
>>> import os.path >>> os.path.abspath(".") 'C:\books\python'
Modules can be imported by importing the modules specifically from the package. Items in submodules can be accessed implicitly without the package name:
>>> from os import path >>> path.abspath(".") 'C:\books\python'
Python includes a reload(
module
)
function that reloads a module. This can be extremely useful during development if you need to update a module and reload it without terminating your program. However, objects created before the module is reloaded are not updated, so you must be careful in handling those objects.
Python classes are basically a collection of attributes and methods. Classes are typically used for one of two purposes: to create a whole new user-defined data type or to extend the capabilities of an existing one. This section assumes that you have a fair understanding of classes from C, Java, or other object-oriented language.
In Python, classes are extremely easy to define and instantiate (create new class object). Use the class name
(object
):
statement to define a new class, where the name
is your own user-defined object type and the object
specifies the Python object from which to inherit.
Class inheritance in Python is similar to that in Java, C, and other object-oriented languages. The methods and attributes of the parent class will be available from the child, and any methods or attributes with the same name in the child will override the parents’.
All code contained in the block following the class statement will be executed each time the class is instantiated. The code sample testClass.py
illustrates how to create a basic class in Python. The class
statement sets the name of the class type and inherits from the base object
class.
The class
statement only defines the class object type; it does not create a class object. The class
object will still need to be created by calling the class directly.
The __init__()
function overrides the method inherited from the object class and will be called when the class is instantiated. The class is instantiated by calling it directly: tc = testCLass("Five")
. When the class is called directly, an instance of the class object is returned.
You can specify any necessary parameters to the __init__()
function as long as you provide the parameters when calling the class to create a class object.
class testClass(object): print "Creating New Class ==================" number=5 def __init__(self, string): self.string = string def printClass(self): print "Number = %d"% self.number print "String = %s"% self.string tc = testClass("Five") tc.printClass() tc.number = 10 tc.string = "Ten" tc.printClass()
testClass.py
Creating New Class ================== Number = 5 String = Five Number = 10 String = Ten
Output from testClass.py code.
Defining and calling functions in Python is typically pretty easy; however, it can become extremely convoluted. The best thing to keep in mind is that functions are objects in the Python language and the parameters that are passed are really “applied” to the function object.
To create a function, use the def functionname(
parameters
):
statement, and then define the function in the following code block. Once the function has been defined, you can call it by specifying the function name and passing the appropriate parameters.
That being said, the following paragraphs show some of the different ways to accomplish that simple task for the function shown here:
def fun(name, location, year=2006): print "%s/%s/%d" % (name, location, year)
The first example shows the function being called by passing the parameter values in order. Notice that the year
parameter has a default value set in the function definition, which means that this parameter can be omitted and the default value will be used.
>>>fun("Teag", "San Diego") Teag/San Diego/2006
The next example shows passing the parameters by name. The advantage of passing parameters by name is that the order in which they appear in the parameter list does not matter.
>>>fun(location="L.A.", year=2004, name="Caleb" ) Caleb/L.A./2004
This example illustrates the ability to mix different methods of passing the parameters. In the example, the first parameter is passed as a value, and the second and third are passed as an assignment.
>>>fun("Aedan", year=2005, location="London") Aedan/London/2005
Parameters can also be passed as a tuple using the *
syntax, as shown in this example. The items in the tuple must match the parameters that are expected by the function.
>>>tuple = ("DaNae", "Paris", 2003) >>>fun(*tuple) DaNae/Paris/2003
Parameters can also be passed as a dictionary using the **
syntax, as shown in this example. The entries in the dictionary must match the parameters that are expected by the function.
>>>dictionary = {'name':'Brendan', 'location':'Orlando', 'year':1999} >>>fun(**dictionary) Brendan/Orlando/1999
Values can be returned from functions using the return
statement. If a function has no return
statement, then a None
object is returned. The following example shows a simple square function that accepts a number and returns the square of the number:
>>> def square(x): ... return x*x ... >>> print square(3) 9
Functions can be treated as any other Python object. In addition to being called, they can be assigned as a value to a list or dictionary, passed as an argument, returned as a value, and so on.
The lambda
operator built in to the Python language provides a method to create anonymous functions. This makes it easier to pass simple functions as parameters or assign them to variable names. The lambda
operator uses the following syntax to define the function:
lambda <args> : <expression>
The term args
refers to a list of arguments that get passed to the function. The term expression
can be any legal Python expression. The following code shows an example of using the lambda
operator to assign an anonymous function to a variable:
>>>bigger = lambda a, b : a > b >>>print bigger(1,2) False >>>print bigger(2,1) True
Scoping in Python revolves around the concept of namespaces. Namespaces are basically dictionaries containing the names and values of the objects within a given scope. There are four basic types of namespaces that you will be dealing with: the global, local, module, and class namespaces.
Global namespaces are created when a program begins execution. The global namespace initially includes built-in information about the module being executed. As new objects are defined in the global namespace scope, they are added to the namespace. The global namespace is accessible from all scopes, as shown in the example where the global value of x
is retrieved using globals()["x"]
.
You can look at the global namespace using the globals()
function, which returns a dictionary object that includes all entries in the global namespace.
Local namespaces are created when a function is called. Local namespaces are nested with functions as they are nested. Name lookups begin in the most nested namespace and move out to the global namespaces.
The global
statement forces names to be linked to the global namespace rather than to the local namespace. In the sample code, we use the global
statement to force the name x
to point to the global namespace. When x
is changed, the global object will be modified.
Although objects can be seen in outer nested namespaces, only the most local and global namespaces can be modified. In the sample code, the variable b
from fun
can be referenced for value in the sub
function; however, modifying its value in sub
would not change the value in fun
.
x = 1 def fun(a): b=3 x=4 def sub(c): d=b global x x = 7 print ("Nested Function =================") print locals() sub(5) print (" Function =================") print locals() print locals()["x"] print globals()["x"] print (" Globals =================") print globals() fun(2)
scope.py
Globals ================= {'x': 1, '__file__': 'C:\books\python\CH1\code\scope.py', 'fun': <function fun at 0x008D7570>, 't': <class '__main__.t'>, 'time': <module 'time' (built-in)>,. . .} Nested Function ================= {'c': 5, 'b': 3, 'd': 3} Function ================= {'a': 2, 'x': 4, 'b': 3, 'sub': <function sub at 0x008D75F0>} 4 7
The module namespace is created when a module is imported and the objects within the module are read. The module namespace can be accessed using the .__dict__
attribute of the module object. Objects in the module namespace can be accessed directly using the module name and dot “.” syntax. The example shows this by calling the localtime()
function of the time module:
>>>import time >>>print time.__dict__ {'ctime': <built-in function ctime>, 'clock': <built-in function clock>, ... 'localtime': <built-in function localtime>} >>> print time.localtime() (2006, 8, 10, 14, 32, 39, 3, 222, 1)
The class namespace is similar to the module namespace; however, it is created in two parts. The first part is created when the class is defined, and the second part is created when the class is instantiated. The module namespace can also be accessed using the .__dict__
attribute of the class object.
Notice in the sample code that x
resides in t.__dict__
and double
resides in tClass__dict__
, yet both are accessible using the dot syntax of the instantiated class object.
Objects in the class namespace can be accessed directly using the module name and dot “.” syntax. The example shows this in the print t.x
and t.double()
statements:
>>>class tClass(object): >>> def__init__(self, x): >>> self.x = x >>> def double(self): >>> self.x += self.x >>>t = tClass (5) >>>print t.__dict__ {'x': 5} >>>print tClass.__dict__ {'__module__': '__main__', 'double': <function double at 0x008D7570>, . . . } >>>print t.x 5 >>>t.double() >>>print t.x 5
Error handling in Python is done through the use of exceptions that are caught in try
blocks and handled in except
blocks. If an error is encountered, a try
block code execution is stopped and transferred down to the except
block, as shown in the following syntax:
try: f = open("test.txt") except IOError: print "Cannot open file."
The exception type
value refers to either one of the built-in Python exceptions or a custom-defined exception object. The error
value is a variable to capture the data returned by the exception.
The try
block also supports the use of an else
block after the last except
block. The else
block is executed if the try
block finishes without receiving an exception.
In addition to using an except
block after the try
block, you can also use the finally
block. The code in the finally
block will be executed regardless of whether an exception occurs. If no exception occurs, the finally
block will be executed after the try
block. If an exception occurs, the execution immediately is transferred to the finally
block, and then the exception continues until it is handled. The following code shows an example of using finally
to force a file to be closed even if an exception occurs:
f = open("test.txt") try: f.write(data) . . . finally: f.close()
You can raise an exception in your own program by using the raise
exception
[, value]
statement. The value of exception
is one of the built-in Python exceptions or a custom-defined exception object. The value of value
is a Python object that you create to give details about the exception. Raising an exception breaks current code execution and returns the exception back until it is handled. The following example shows how to raise a generic RuntimeError
exception with a simple text message value:
raise RuntimeError, "Error running script"
One of the most useful features of the Python language is the set of modules that provide access to the local computer system. These modules provide access to such things as the file system, OS, and shell, as well as various system functions.
This section discusses using the os
, sys
, platform
, and time
modules to access some of the more commonly used system information.
The os
module provides a portable platform-independent interface to access common operating services, allowing you to add OS-level support to your programs. The following examples illustrate some of the most common uses of the os module.
The os.path.abspath(
path
)
function of the os module returns a string version of the absolute path of the path specified. Because abspath
takes into account the current working directory, the .
and ..
directory options will work as shown next:
>>>print os.path.abspath(".") >>>C:ookspythonch1 print os.path.abspath("..") C:ookspython
The os.path
module provides the exists(
path
)
, isdir(
path
)
, and isfile(
path
)
function to check for the existence of files and directories, as shown here:
>>>print os.path.exists("/books/python/ch1") True >>>print os.path.isdir("/books/python/ch1") True >>>print os.path.isfile("/books/python/ch1/ch1.doc") True
The os.chdir(
path
)
function provides a simple way of changing the current working directory for the program, as follows:
>>>os.chdir("/books/python/ch1/code") >>>print os.path.abspath(".") C:ookspythonCH1code
The os.environ
attribute contains a dictionary of environmental variables. You can use this dictionary as shown next to access the environmental variables of the system:
>>>print os.environ['PATH'] C:WINNTsystem32;C:WINNT;C:Python24
The os.system(
command
)
function will execute a system function as if it were in a subshell, as shown with the following dir
command:
>>>os.system("dir") Volume Serial Number is 98F3-A875 Directory of C:ookspythonch1code 08/11/2006 02:10p <DIR> . 08/11/2006 02:10p <DIR> .. 08/10/2006 04:00p 405 format.py 08/10/2006 10:27a 546 function.py 08/10/2006 03:07p 737 scope.py 08/11/2006 02:58p 791 sys_tools.py 4 File(s) 3,717 bytes 2 Dir(s) 7,880,230,400 bytes free
Python provides a number of exec
type functions to execute applications on the native system. The following example illustrates using the os.execvp(
path, args
)
function to execute the application update.exe
with a command-line parameter of -verbose
:
>>>os.execvp("update.exe", ["-verbose"])
The sys
module provides an interface to access the environment of the Python interpreter. The following examples illustrate some of the most common uses of the sys
module.
The argv
attribute of the sys
module is a list. The first item in the argv
list is the path to the module; the rest of the list is made up of arguments that were passed to the module at the beginning of execution. The sample code shows how to use the argv
list to access command-line parameters passed to a Python module:
>>>print sys.argv ['C:\books\python\CH1\code\print_it.py', 'text'] >>>print sys.argv[1] text
The stdin
attribute of the sys
module is a file object that gets created at the start of code execution. In the following sample code, text is read from stdin
(in this case, the keyboard, which is the default) using the readline()
function:
>>>text = sys.stdin.readline() >>>print text Input Text
The sys
module also has the stdout
and stderr
attributes that point to files used for standard output and standard error output. These files default to writing to the screen. The following sample code shows how to redirect the standard output and standard error messages to a file rather than to the screen:
>>>sOUT = sys.stdout >>>sERR = sys.stderr >>>sys.stdout = open("ouput.txt", "w") >>>sys.stderr = sys.stdout >>>sys.stdout = sOUT >>>sys.stderr = sERR
The platform
module provides a portable interface to information about the platform on which the program is being executed. The following examples illustrate some of the most common uses of the platform
module.
The platform.architecture()
function returns the (bits, linkage
) tuple that specifies the number of bits for the system word size and linkage information about the Python executable:
>>>print platform.architecture() ('32bit', '')
The platform.python_version()
function returns the version of the Python executable for compatibility purposes:
>>>print platform.python_version() 2.4.2
The platform.uname()
function returns a tuple in the form of (system, node, release, version, machine, processor
). System refers to which OS is currently running, node refers to the host name of the machine, release refers to the major release of the OS, version refers to a string representing OS release information, and machine and processor refer to the hardware platform information.
>>>print platform.uname() ('Linux', 'bwd-linux', '2.6.16-20-smp', '#1 SMP Mon Apr 10 04:51:13 UTC 2006', 'i686', 'i686')
The time
module provides a portable interface to time functions on the system on which the program is executing. The following examples illustrate some of the most common uses of the time
module.
The time.time()
function returns the current system time in terms of the number of seconds since the UTC (Coordinated Universal Time). This value is typically collected at various points in the program and is used in delta operations to determine the amount of time since an event occurred.
>>>print time.time() 1155333864.11
The time.localtime(
secs
)
function returns the time, specified by secs since the UTC, in the form of tuple (year, month, day, hour, minute, second, day of week, day of year, daylight savings). If no time is specified, the current time is used as follows:
>>>print time.localtime() (2006, 8, 11, 16, 4, 24, 4, 223, 1)
The time.ctime(
secs
)
function returns the time, specified by secs since the UTC, as a formatted, printable string. If no time is specified, then the current time is used as shown here:
>>>print time.ctime() Fri Aug 11 16:04:24 2006
The time.clock()
function returns the current CPU time as a floating-point number that can be used for various timing functions:
>>>print time.clock() 5.02857206712e-006
The time.sleep(
sec
)
function forces the current process to sleep for the number of seconds specified by the floating-point number secs:
>>>time.sleep(.5)