PBE logo

os - Operating system interfaces

Note

Currently, functions available in Unix only are not listed in this document, they will be added later.

name
name of the Operating System.
>>> name
'nt'
environ
dictionary representing environment variables.

Note

This mapping is captured the first time the os module is imported, typically during Python startup as part of processing site.py. Changes to the environment made after this time are not reflected in os.environ, except for changes made by modifying os.environ directly.

>>> environ["home"]
'e:\\cygwin\\home\\ak'
>>> environ["user"]
'ak'
chdir(path)
fchdir(fd)
getcwd()
change current working directory to path, to file descriptor (must be an fd of an open directory), get current working directory.
>>> getcwd()
'e:\\Home\\Projects\\py-by-example\\test'
>>> chdir('..')
>>> getcwd()
'e:\\Home\\Projects\\py-by-example'
getpid()
get current process id
getpid() # 484
getenv(varname[, value])
get environment var or value if it does not exist.
>>> getenv('home')
'e:\\cygwin\\home\\ak'
setenv(varname, value)
unsetenv(varname)
set environment var to value, delete env. variable. Such changes to the environment affect subprocesses started with os.system(), popen() or fork() and execv(). Also unsetenv(varname)
putenv('home', 'e:\\cygwin\\home\\ak\\newhome')
strerror(code)
error message corresponding to code.
>>> strerror(1)
'Operation not permitted'
>>> strerror(0)
'No error'
>>> strerror(2)
'No such file or directory'
>>> strerror(3)
'No such process'
umask(mask)
Set current numeric umask and return the previous one.
fdopen(fd[, mode[, bufsize]])
return an open file object connected to file descriptor fd.
>>> fp = open('test', 'w')
>>> d = fp.fileno()
>>> d
3
>>> os.fdopen(d)
<open file '<fdopen>', mode 'r' at 0x0098A530>
popen(command[, mode[, bufsize]])
deprecated since 2.6, use subprocess module instead. (This applies to all os.popen* functions)
access(path, mode)
test specified access to path.
>>> access('.', F_OK)           # read access
True
>>> access('.', X_OK)           # execute access
True
>>> access('.', X_OK | W_OK)    # execute and write
True
chmod(path, mode)
change mode of path, the only mode available in Windows is read-only, see stat module for modes available in Unix.
chmod("myfile.txt", stat.S_IREAD)   # set read-only flag
listdir(path)
return a list of dir contents.
>>> listdir('.')
['.bashrc', '.bash_history', '.bash_profile', '.build', '.inputrc',
'.static', ' .templates', 'conf.py', 'home.lnk', 'index.rst', 'km.lnk',
'projects.lnk', 'test.txt', 'test2.txt', '_viminfo']
mkdir(path[, mode])
create a directory.
mkdir("mydir")
makedirs(path[, mode])
create a directory, making intermediate-level directories needed to contain the leaf dir.
makedirs("firstdir/seconddir/mydir")
remove(path)
delete file (not a directory.)
remove("my_file.txt")
removedirs(path)
delete directories recursively.
removedirs("foo/bar/baz")
# first try to remove dir baz, if successful, remove bar, then foo
rename(src, dst)
rename file or directory.
rename("myfile.txt", "newfile.txt")
renames(src, dst)
recursive directory or file renaming - tries to create all intermediary directories as needed.

Note

This function can fail with the new directory structure made if you lack permissions needed to remove the leaf directory or file.

renames("myfile.txt", "mydir/newfile.txt")
rmdir(path)
remove directory path, directory must be empty or an OSError is raised.
rmdir("mydir")
stat(path)
perform stat system call on the given path.

Changed in version 2.5: Added st_gen and st_birthtime.

>>> statinfo = os.stat('somefile.txt')
>>> statinfo
(33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732,
    1105022732)
# tuple items in order are:
# st_mode (protection bits), st_ino (inode number), st_dev (device),
# st_nlink (number of hard links), st_uid (user id of owner),
# st_gid (group id of owner), st_size (size of file, in bytes),
# st_atime (time of most recent access), st_mtime (time of most recent
# content modification), st_ctime (platform dependent; time of most
# recent metadata change on Unix, or the time of creation on Windows)

statinfo.st_size
# 926L
utime(path, times)
Set access and modified times, times can be None to set them to current time (similar to Unix touch command), otherwise times has to be a tuple (atime, mtime).
utime("myfile.txt", None)       # similar to Unix 'touch' command
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])

Changed in version 2.6: The followlinks parameter.

# For this example we have dir structure:
# somedir
#   dir1
#   dir2
#       dir3
#           file.txt

>>> for (dirpath, dirnames, filenames) in walk('somedir'):
...     print dirpath, dirnames, filenames

somedir ['dir1', 'dir2'] ['test.txt']
somedir\dir1 [] []
somedir\dir2 ['dir3'] []
somedir\dir2\dir3 [] ['file.txt']

This example displays the number of bytes taken by non-directory files in each directory under the starting directory, except that it doesn’t look under any CVS subdirectory:

# example taken from LibRef
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
    print root, "consumes",
    print sum(getsize(join(root, name)) for name in files),
    print "bytes in", len(files), "non-directory files"
    if 'CVS' in dirs:
        dirs.remove('CVS')  # don't visit CVS directories

In the next example, walking the tree bottom-up is essential: rmdir() doesn’t allow deleting a directory before the directory is empty:

# example taken from LibRef
# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        os.remove(os.path.join(root, name))
    for name in dirs:
        os.rmdir(os.path.join(root, name))
abort()
Generate a SIGABRT signal to the current process. On Unix, the default behavior is to produce a core dump; on Windows, the process immediately returns an exit code of 3. Be aware that programs which use signal.signal() to register a handler for SIGABRT will behave differently. Availability: Unix, Windows.

Example in windows command line interpreter:

>>> abort()

This application has requested the Runtime to terminate it in an
unusual way.
Please contact the application's support team for more information.
execl(path, arg0, arg1, ...)
execle(path, arg0, arg1, ..., env)
execlp(file, arg0, arg1, ...)
execlpe(file, arg0, arg1, ..., env)
execv(path, args)
execve(path, args, env)
execvp(file, args)
execvpe(file, args, env)
>>> execl("e:\python26\python", "python", "-V")

ak@ak-65e460dcbdaf ~/projects/py-by-example/test
$ Python 2.6.1

Note that running python interpreter shell was replaced by given command, which printed out version and exited, dropping us back to shell, in this case Cygwin.

The following example is the same but with environment provided by the last arg:

>>> execle("e:\python26\python", "python", "-V", {"HOME":"e:\\"})

ak@ak-65e460dcbdaf ~/projects/py-by-example/test
$ Python 2.6.1
>>> execlp("python", "python", "-V")

ak@ak-65e460dcbdaf ~/projects/py-by-example/test
$ Python 2.6.1
>>> execv("python", ("python", "-V"))

ak@ak-65e460dcbdaf ~/projects/py-by-example/test
$ Python 2.6.1

Of the exec* functions, the ones that end with an ‘e’ require a dictionary of environment variables, those ending in ‘p’ use PATH variable from environment, the ones ending in ‘l’ take parameters from exec* function and call the command; the ones ending in ‘v’ take parameters from the tuple as shown.

startfile(path[, operation])
Start a file with associated application.
startfile("test.txt")
# test.txt will be opened by associated text editor
system(command)
Execute the command in a subshell.
>>> system("ls -l")
total 351
-rw-r--r--  1 ak None  6344 Feb 24 03:32 array-module.rst
...
times()
return processor times.
>>> times()
(0.03125, 0.125, 0.0, 0.0, 0.0)
# user time, system time, children's user time, children's system time,
# and elapsed real time since a fixed point in the past
# (on Windows only first two items are filled)
urandom(n)
Return a string of n random bytes suitable for cryptographic use.
>>> urandom(10)
'\x8a"\xdc\xdb.\xec\x822k\x8f'