⇤ ← Revision 1 as of 2008-11-07 13:03:59
Size: 2566
Comment:
|
Size: 3272
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 49: | Line 49: |
* {{{os.walk()}}} Directory tree generator | |
Line 50: | Line 51: |
=== System programming: walk example === The following script walks through a directory tree and looks for all files with the matching extension: {{{#!python #!/usr/bin/env python import os,fnmatch,sys # Usage: # ./walkdir.py directory extension dir,ext=sys.argv[1],sys.argv[2] for root, dirs, files in os.walk(dir): f=fnmatch.filter(files,'*.'+ext) if type(f)==type([]): for fi in f: print root+fi }}} Save the file as {{{walkdir.py}}} and use {{{chmod +x walkdir.py}}} to set the execution permissions of the file. The script can be exectuted on the bash shell using: {{{./walkdir.py $HOME/subdir ps}}} |
Contents
Interaction with the operating system
The modules sys and os provide the basic interface to the operating system. The module os creates a portable abstraction layer which is used by high-level modules like glob, socket, thred, time, fcntl.
Module sys
The module sys provides access to system-specific parameters by the interpreter.
Example argv
run system1.py parameter1 parameter2 ['system1.py', 'parameter1', 'parameter2']
The script prints the command line arguments that are passed to the script. argv[0] is the script name
A more sophisticated way of evaluating command line arguments is provided by the module optparse
Module os
The module os is a portable operating system interface.
Some examples:
os.system() Executes the command (a string) in a subshell
os.mkdir() Creates a directory
os.remove() Deletes a file
os.path.isdir() Test if directory
os.path.isfile() Test if file
os.path.exists() Test if file or directory exists
os.path.getsize() Size of a file
os.path.basename() Base name of pathname
os.walk() Directory tree generator
System programming: walk example
The following script walks through a directory tree and looks for all files with the matching extension:
Save the file as walkdir.py and use chmod +x walkdir.py to set the execution permissions of the file. The script can be exectuted on the bash shell using: ./walkdir.py $HOME/subdir ps
Module glob
The module glob finds all the pathnames matching a specified pattern according to the rules used by the Unix shell.
The following example looks for all pdf files in the current working directory and converts them into postscript files.
Unix Specific Services
Features that are unique to the Unix operating system are for example shell pipelines (data streams) that pipe the output of one program to another. The pipeline symbol is |. For example, the command ls -s | sort -rg pipes the output of ls -s to the sort program. The result is a list of filenames sorted by its size
A python pipeline to a Unix programm can be established using the module pipes