Python System Services and System Calls
July 30, 2009
|
Phillip Watts explores some of the
most common and useful Python system tools.
|
All operating systems have services. At the highest
levels, these give users abilities like running programs,
viewing and setting environment variables, and renaming
files on the hard drive. High level languages like C++,
Java, and Python have libraries which give the programmer
access to services. These libraries usually contain classes,
which contain methods and properties, which are the
abstractions of the operating system services.
In Python, many of these services are contained in the modules
sys, os, and os.path. This article will explore some of the
most common and useful of these system tools.
Here are some examples from the sys module, which might be useful:
$ python
>>> import sys
>>> sys.stdin
<open file '<stdin>', mode 'r' at 0xb7d44020>
>>> sys.platform
'linux2'
>>> sys.version
'2.5.1 (r251:54863, May 2 2007, 16:56:35) \n[GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)]'
>>> sys.getrecursionlimit()
1000
Now let us look at couple of more features of the sys module:
#!/usr/bin/env python
# sample.py
import sys
arglist = sys.argv
print arglist
sys.exit()
$ python sample.py filea fileb
['sample.py', 'filea', 'fileb']
sys.argv is a list of the command line
arguments to the program. We can see that the first item in
the list is the program itself. sys.exit()
exits the python interpreter.
The 'os' module contains many useful tools for file
manipulation, such as removing, renamimg, and seeking within
a file. Let's write a simple program which finds if all the
files in one directory are also in another directory.
#!/usr/bin/env python
import sys, os
arglist = sys.argv
if len(arglist) != 3:
print "Need two dir names as args."
print
sys.exit()
dir1 = arglist[1]
dir2 = arglist[2]
if not os.path.isdir(dir1):
print dir1,'is not a directory'
sys.exit()
if not os.path.isdir(dir2):
print dir2,'is not a directory'
sys.exit()
list1 = os.listdir(dir1)
list2 = os.listdir(dir2)
list1.sort()
for filen in list1:
if not os.path.exists(dir2 + '/' + filen):
print filen
Python System Services and System Calls
Python System Services and System Calls - Cont.
|