os module provides operating system dependent functionality. You can import it using the following import statement.
>>> import os
getuid() function returns the current process's effective user's id.
>>> os.getuid()
500
getpid() returns the current process's id.
getppid() returns the parent process's id.
>>> os.getpid()
16150
>>> os.getppid()
14847
uname() returns different information identifying the operating system, in Linux it returns details you can get from the
uname command. The returned object is a tuple,
(sysname, nodename, release, version, machine)
>>> os.uname()
('Linux', 'd80', '2.6.34.7-56.fc13.i686.PAE', '#1 SMP Wed Sep 15 03:27:15 UTC 2010', 'i686')
getcwd()returns the current working directory.
chdir(path) changes the current working directory to path. In the example we first see the current directory which is my home directory and change the current directory to
/tmp and then again checking the current directory.
>>> os.getcwd()
'/home/kushal'
>>> os.chdir('/tmp')
>>> os.getcwd()
'/tmp'
So let us use another function provided by the os module and create our own function to list all files and directories in any given directory.
def view_dir(path='.'):
names = os.listdir(path)
names.sort()
for name in names:
print name,
>>> view_dir('/')
.readahead bin boot dev etc home junk lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var