Using System Tools


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.

os Module

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:\books\python\ch1\ print os.path.abspath("..") C:\books\python\


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:\books\python\CH1\code


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:\WINNT\system32;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:\books\python\ch1\code 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"])


sys Module

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


platform Module

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')


time Module

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)




Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net