Interacting with the UNIX System


The module os (operating system) allows Python to interact directly with the files on your system and to run UNIX commands from within a script.

File Manipulation

One of the commonly used functions in os is os.path.isfile(), which checks if a file exists:

 import os, sys if not os.path.isfile (argv[1]) :     sys.stderr.write("Error: %s is not a valid filename\n" % argv[1])

Similarly, os.path.isdir() can be used to see if a string is a valid directory name. The function os.path.exists() checks if a pathname (for either a file or a directory) is valid.

To get a list of the files in a directory, you can use os.listdir(), as in

 for filename in os.listdir("/home/alice") :     print filename

The list will include hidden files such as .profile. You can get the path of the current directory with os.getcwd(), so you can get a list of the files in the current directory with

 filelist = os .listdir (os.getcwd())

A few of the other useful functions included in the os module are mkdir(), which creates a directory, rename(), which moves a file, and remove(), which deletes a file. To copy files, you can use the module shutil, which has the functions copy(), to copy a single file, and copytree(), to recursively copy a directory For example,

 shutil.copytree(projectdir, projectdir + ".bak")

will copy the files in projectdir to a backup directory

Running UNIX Commands

You can run a UNIX command in your script with os.system(). For example, you could call uname -a (which displays the details about your machine, including the operating system, hostname, and processor type) like this:

 os.system("uname -a")             # Print system information

However, os.system() does not return the output from uname -a, which is sent directly to standard output. To work with the output from a command, you must open a pipe.

Opening Pipelines

Python lets you open pipes to or from other commands with os.popen(). For example,

 readpipe = os.popen("ls -la", 'r')           # Similar to ls -la pythonscript.py

will allow you to read the output from ls -la with readpipe, just as you would read input from sys.stdin. For example, you could print each line of input from readpipe:

 for line in readpipe.readlines() :    print line.rstrip()

You can also open a command to accept output. For example,

 writepipe=os.popen("lpr", 'w')        # Similar to pythonscript.py lpr writepipe.write(printdata)             # Send printdata to printer

will let you send output to lpr.




UNIX. The Complete Reference
UNIX: The Complete Reference, Second Edition (Complete Reference Series)
ISBN: 0072263369
EAN: 2147483647
Year: 2006
Pages: 316

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