PageRenderTime 194ms CodeModel.GetById 20ms app.highlight 109ms RepoModel.GetById 2ms app.codeStats 1ms

/Doc/library/os.rst

http://unladen-swallow.googlecode.com/
ReStructuredText | 2154 lines | 1376 code | 778 blank | 0 comment | 0 complexity | 3f385f38c7506dc5e3ab477140efda3d MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1:mod:`os` --- Miscellaneous operating system interfaces
   2=======================================================
   3
   4.. module:: os
   5   :synopsis: Miscellaneous operating system interfaces.
   6
   7
   8This module provides a portable way of using operating system dependent
   9functionality.  If you just want to read or write a file see :func:`open`, if
  10you want to manipulate paths, see the :mod:`os.path` module, and if you want to
  11read all the lines in all the files on the command line see the :mod:`fileinput`
  12module.  For creating temporary files and directories see the :mod:`tempfile`
  13module, and for high-level file and directory handling see the :mod:`shutil`
  14module.
  15
  16The design of all built-in operating system dependent modules of Python is such
  17that as long as the same functionality is available, it uses the same interface;
  18for example, the function ``os.stat(path)`` returns stat information about
  19*path* in the same format (which happens to have originated with the POSIX
  20interface).
  21
  22Extensions peculiar to a particular operating system are also available through
  23the :mod:`os` module, but using them is of course a threat to portability!
  24
  25.. note::
  26
  27   If not separately noted, all functions that claim "Availability: Unix" are
  28   supported on Mac OS X, which builds on a Unix core.
  29
  30.. note::
  31
  32   All functions in this module raise :exc:`OSError` in the case of invalid or
  33   inaccessible file names and paths, or other arguments that have the correct
  34   type, but are not accepted by the operating system.
  35
  36
  37.. exception:: error
  38
  39   An alias for the built-in :exc:`OSError` exception.
  40
  41
  42.. data:: name
  43
  44   The name of the operating system dependent module imported.  The following names
  45   have currently been registered: ``'posix'``, ``'nt'``, ``'mac'``, ``'os2'``,
  46   ``'ce'``, ``'java'``, ``'riscos'``.
  47
  48
  49.. _os-procinfo:
  50
  51Process Parameters
  52------------------
  53
  54These functions and data items provide information and operate on the current
  55process and user.
  56
  57
  58.. data:: environ
  59
  60   A mapping object representing the string environment. For example,
  61   ``environ['HOME']`` is the pathname of your home directory (on some platforms),
  62   and is equivalent to ``getenv("HOME")`` in C.
  63
  64   This mapping is captured the first time the :mod:`os` module is imported,
  65   typically during Python startup as part of processing :file:`site.py`.  Changes
  66   to the environment made after this time are not reflected in ``os.environ``,
  67   except for changes made by modifying ``os.environ`` directly.
  68
  69   If the platform supports the :func:`putenv` function, this mapping may be used
  70   to modify the environment as well as query the environment.  :func:`putenv` will
  71   be called automatically when the mapping is modified.
  72
  73   .. note::
  74
  75      Calling :func:`putenv` directly does not change ``os.environ``, so it's better
  76      to modify ``os.environ``.
  77
  78   .. note::
  79
  80      On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
  81      cause memory leaks.  Refer to the system documentation for
  82      :cfunc:`putenv`.
  83
  84   If :func:`putenv` is not provided, a modified copy of this mapping  may be
  85   passed to the appropriate process-creation functions to cause  child processes
  86   to use a modified environment.
  87
  88   If the platform supports the :func:`unsetenv` function, you can delete items in
  89   this mapping to unset environment variables. :func:`unsetenv` will be called
  90   automatically when an item is deleted from ``os.environ``, and when
  91   one of the :meth:`pop` or :meth:`clear` methods is called.
  92
  93   .. versionchanged:: 2.6
  94      Also unset environment variables when calling :meth:`os.environ.clear`
  95      and :meth:`os.environ.pop`.
  96
  97
  98.. function:: chdir(path)
  99              fchdir(fd)
 100              getcwd()
 101   :noindex:
 102
 103   These functions are described in :ref:`os-file-dir`.
 104
 105
 106.. function:: ctermid()
 107
 108   Return the filename corresponding to the controlling terminal of the process.
 109   Availability: Unix.
 110
 111
 112.. function:: getegid()
 113
 114   Return the effective group id of the current process.  This corresponds to the
 115   "set id" bit on the file being executed in the current process. Availability:
 116   Unix.
 117
 118
 119.. function:: geteuid()
 120
 121   .. index:: single: user; effective id
 122
 123   Return the current process's effective user id. Availability: Unix.
 124
 125
 126.. function:: getgid()
 127
 128   .. index:: single: process; group
 129
 130   Return the real group id of the current process. Availability: Unix.
 131
 132
 133.. function:: getgroups()
 134
 135   Return list of supplemental group ids associated with the current process.
 136   Availability: Unix.
 137
 138
 139.. function:: getlogin()
 140
 141   Return the name of the user logged in on the controlling terminal of the
 142   process.  For most purposes, it is more useful to use the environment variable
 143   :envvar:`LOGNAME` to find out who the user is, or
 144   ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the currently
 145   effective user id. Availability: Unix.
 146
 147
 148.. function:: getpgid(pid)
 149
 150   Return the process group id of the process with process id *pid*. If *pid* is 0,
 151   the process group id of the current process is returned. Availability: Unix.
 152
 153   .. versionadded:: 2.3
 154
 155
 156.. function:: getpgrp()
 157
 158   .. index:: single: process; group
 159
 160   Return the id of the current process group. Availability: Unix.
 161
 162
 163.. function:: getpid()
 164
 165   .. index:: single: process; id
 166
 167   Return the current process id. Availability: Unix, Windows.
 168
 169
 170.. function:: getppid()
 171
 172   .. index:: single: process; id of parent
 173
 174   Return the parent's process id. Availability: Unix.
 175
 176
 177.. function:: getuid()
 178
 179   .. index:: single: user; id
 180
 181   Return the current process's user id. Availability: Unix.
 182
 183
 184.. function:: getenv(varname[, value])
 185
 186   Return the value of the environment variable *varname* if it exists, or *value*
 187   if it doesn't.  *value* defaults to ``None``. Availability: most flavors of
 188   Unix, Windows.
 189
 190
 191.. function:: putenv(varname, value)
 192
 193   .. index:: single: environment variables; setting
 194
 195   Set the environment variable named *varname* to the string *value*.  Such
 196   changes to the environment affect subprocesses started with :func:`os.system`,
 197   :func:`popen` or :func:`fork` and :func:`execv`. Availability: most flavors of
 198   Unix, Windows.
 199
 200   .. note::
 201
 202      On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
 203      cause memory leaks. Refer to the system documentation for putenv.
 204
 205   When :func:`putenv` is supported, assignments to items in ``os.environ`` are
 206   automatically translated into corresponding calls to :func:`putenv`; however,
 207   calls to :func:`putenv` don't update ``os.environ``, so it is actually
 208   preferable to assign to items of ``os.environ``.
 209
 210
 211.. function:: setegid(egid)
 212
 213   Set the current process's effective group id. Availability: Unix.
 214
 215
 216.. function:: seteuid(euid)
 217
 218   Set the current process's effective user id. Availability: Unix.
 219
 220
 221.. function:: setgid(gid)
 222
 223   Set the current process' group id. Availability: Unix.
 224
 225
 226.. function:: setgroups(groups)
 227
 228   Set the list of supplemental group ids associated with the current process to
 229   *groups*. *groups* must be a sequence, and each element must be an integer
 230   identifying a group. This operation is typically available only to the superuser.
 231   Availability: Unix.
 232
 233   .. versionadded:: 2.2
 234
 235
 236.. function:: setpgrp()
 237
 238   Call the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on
 239   which version is implemented (if any).  See the Unix manual for the semantics.
 240   Availability: Unix.
 241
 242
 243.. function:: setpgid(pid, pgrp)
 244
 245   Call the system call :cfunc:`setpgid` to set the process group id of the
 246   process with id *pid* to the process group with id *pgrp*.  See the Unix manual
 247   for the semantics. Availability: Unix.
 248
 249
 250.. function:: setreuid(ruid, euid)
 251
 252   Set the current process's real and effective user ids. Availability: Unix.
 253
 254
 255.. function:: setregid(rgid, egid)
 256
 257   Set the current process's real and effective group ids. Availability: Unix.
 258
 259
 260.. function:: getsid(pid)
 261
 262   Call the system call :cfunc:`getsid`.  See the Unix manual for the semantics.
 263   Availability: Unix.
 264
 265   .. versionadded:: 2.4
 266
 267
 268.. function:: setsid()
 269
 270   Call the system call :cfunc:`setsid`.  See the Unix manual for the semantics.
 271   Availability: Unix.
 272
 273
 274.. function:: setuid(uid)
 275
 276   .. index:: single: user; id, setting
 277
 278   Set the current process's user id. Availability: Unix.
 279
 280
 281.. placed in this section since it relates to errno.... a little weak
 282.. function:: strerror(code)
 283
 284   Return the error message corresponding to the error code in *code*.
 285   On platforms where :cfunc:`strerror` returns ``NULL`` when given an unknown
 286   error number, :exc:`ValueError` is raised.  Availability: Unix, Windows.
 287
 288
 289.. function:: umask(mask)
 290
 291   Set the current numeric umask and return the previous umask. Availability:
 292   Unix, Windows.
 293
 294
 295.. function:: uname()
 296
 297   .. index::
 298      single: gethostname() (in module socket)
 299      single: gethostbyaddr() (in module socket)
 300
 301   Return a 5-tuple containing information identifying the current operating
 302   system.  The tuple contains 5 strings: ``(sysname, nodename, release, version,
 303   machine)``.  Some systems truncate the nodename to 8 characters or to the
 304   leading component; a better way to get the hostname is
 305   :func:`socket.gethostname`  or even
 306   ``socket.gethostbyaddr(socket.gethostname())``. Availability: recent flavors of
 307   Unix.
 308
 309
 310.. function:: unsetenv(varname)
 311
 312   .. index:: single: environment variables; deleting
 313
 314   Unset (delete) the environment variable named *varname*. Such changes to the
 315   environment affect subprocesses started with :func:`os.system`, :func:`popen` or
 316   :func:`fork` and :func:`execv`. Availability: most flavors of Unix, Windows.
 317
 318   When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is
 319   automatically translated into a corresponding call to :func:`unsetenv`; however,
 320   calls to :func:`unsetenv` don't update ``os.environ``, so it is actually
 321   preferable to delete items of ``os.environ``.
 322
 323
 324.. _os-newstreams:
 325
 326File Object Creation
 327--------------------
 328
 329These functions create new file objects. (See also :func:`open`.)
 330
 331
 332.. function:: fdopen(fd[, mode[, bufsize]])
 333
 334   .. index:: single: I/O control; buffering
 335
 336   Return an open file object connected to the file descriptor *fd*.  The *mode*
 337   and *bufsize* arguments have the same meaning as the corresponding arguments to
 338   the built-in :func:`open` function. Availability: Unix, Windows.
 339
 340   .. versionchanged:: 2.3
 341      When specified, the *mode* argument must now start with one of the letters
 342      ``'r'``, ``'w'``, or ``'a'``, otherwise a :exc:`ValueError` is raised.
 343
 344   .. versionchanged:: 2.5
 345      On Unix, when the *mode* argument starts with ``'a'``, the *O_APPEND* flag is
 346      set on the file descriptor (which the :cfunc:`fdopen` implementation already
 347      does on most platforms).
 348
 349
 350.. function:: popen(command[, mode[, bufsize]])
 351
 352   Open a pipe to or from *command*.  The return value is an open file object
 353   connected to the pipe, which can be read or written depending on whether *mode*
 354   is ``'r'`` (default) or ``'w'``. The *bufsize* argument has the same meaning as
 355   the corresponding argument to the built-in :func:`open` function.  The exit
 356   status of the command (encoded in the format specified for :func:`wait`) is
 357   available as the return value of the :meth:`~file.close` method of the file object,
 358   except that when the exit status is zero (termination without errors), ``None``
 359   is returned. Availability: Unix, Windows.
 360
 361   .. deprecated:: 2.6
 362      This function is obsolete.  Use the :mod:`subprocess` module.  Check
 363      especially the :ref:`subprocess-replacements` section.
 364
 365   .. versionchanged:: 2.0
 366      This function worked unreliably under Windows in earlier versions of Python.
 367      This was due to the use of the :cfunc:`_popen` function from the libraries
 368      provided with Windows.  Newer versions of Python do not use the broken
 369      implementation from the Windows libraries.
 370
 371
 372.. function:: tmpfile()
 373
 374   Return a new file object opened in update mode (``w+b``).  The file has no
 375   directory entries associated with it and will be automatically deleted once
 376   there are no file descriptors for the file. Availability: Unix,
 377   Windows.
 378
 379There are a number of different :func:`popen\*` functions that provide slightly
 380different ways to create subprocesses.
 381
 382.. deprecated:: 2.6
 383   All of the :func:`popen\*` functions are obsolete. Use the :mod:`subprocess`
 384   module.
 385
 386For each of the :func:`popen\*` variants, if *bufsize* is specified, it
 387specifies the buffer size for the I/O pipes. *mode*, if provided, should be the
 388string ``'b'`` or ``'t'``; on Windows this is needed to determine whether the
 389file objects should be opened in binary or text mode.  The default value for
 390*mode* is ``'t'``.
 391
 392Also, for each of these variants, on Unix, *cmd* may be a sequence, in which
 393case arguments will be passed directly to the program without shell intervention
 394(as with :func:`os.spawnv`). If *cmd* is a string it will be passed to the shell
 395(as with :func:`os.system`).
 396
 397These methods do not make it possible to retrieve the exit status from the child
 398processes.  The only way to control the input and output streams and also
 399retrieve the return codes is to use the :mod:`subprocess` module; these are only
 400available on Unix.
 401
 402For a discussion of possible deadlock conditions related to the use of these
 403functions, see :ref:`popen2-flow-control`.
 404
 405
 406.. function:: popen2(cmd[, mode[, bufsize]])
 407
 408   Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
 409   child_stdout)``.
 410
 411   .. deprecated:: 2.6
 412      This function is obsolete.  Use the :mod:`subprocess` module.  Check
 413      especially the :ref:`subprocess-replacements` section.
 414
 415   Availability: Unix, Windows.
 416
 417   .. versionadded:: 2.0
 418
 419
 420.. function:: popen3(cmd[, mode[, bufsize]])
 421
 422   Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
 423   child_stdout, child_stderr)``.
 424
 425   .. deprecated:: 2.6
 426      This function is obsolete.  Use the :mod:`subprocess` module.  Check
 427      especially the :ref:`subprocess-replacements` section.
 428
 429   Availability: Unix, Windows.
 430
 431   .. versionadded:: 2.0
 432
 433
 434.. function:: popen4(cmd[, mode[, bufsize]])
 435
 436   Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
 437   child_stdout_and_stderr)``.
 438
 439   .. deprecated:: 2.6
 440      This function is obsolete.  Use the :mod:`subprocess` module.  Check
 441      especially the :ref:`subprocess-replacements` section.
 442
 443   Availability: Unix, Windows.
 444
 445   .. versionadded:: 2.0
 446
 447(Note that ``child_stdin, child_stdout, and child_stderr`` are named from the
 448point of view of the child process, so *child_stdin* is the child's standard
 449input.)
 450
 451This functionality is also available in the :mod:`popen2` module using functions
 452of the same names, but the return values of those functions have a different
 453order.
 454
 455
 456.. _os-fd-ops:
 457
 458File Descriptor Operations
 459--------------------------
 460
 461These functions operate on I/O streams referenced using file descriptors.
 462
 463File descriptors are small integers corresponding to a file that has been opened
 464by the current process.  For example, standard input is usually file descriptor
 4650, standard output is 1, and standard error is 2.  Further files opened by a
 466process will then be assigned 3, 4, 5, and so forth.  The name "file descriptor"
 467is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
 468by file descriptors.
 469
 470
 471.. function:: close(fd)
 472
 473   Close file descriptor *fd*. Availability: Unix, Windows.
 474
 475   .. note::
 476
 477      This function is intended for low-level I/O and must be applied to a file
 478      descriptor as returned by :func:`os.open` or :func:`pipe`.  To close a "file
 479      object" returned by the built-in function :func:`open` or by :func:`popen` or
 480      :func:`fdopen`, use its :meth:`~file.close` method.
 481
 482
 483.. function:: closerange(fd_low, fd_high)
 484
 485   Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive),
 486   ignoring errors. Availability: Unix, Windows. Equivalent to::
 487
 488      for fd in xrange(fd_low, fd_high):
 489          try:
 490              os.close(fd)
 491          except OSError:
 492              pass
 493
 494   .. versionadded:: 2.6
 495
 496
 497.. function:: dup(fd)
 498
 499   Return a duplicate of file descriptor *fd*. Availability: Unix,
 500   Windows.
 501
 502
 503.. function:: dup2(fd, fd2)
 504
 505   Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary.
 506   Availability: Unix, Windows.
 507
 508
 509.. function:: fchmod(fd, mode)
 510
 511   Change the mode of the file given by *fd* to the numeric *mode*.  See the docs
 512   for :func:`chmod` for possible values of *mode*.  Availability: Unix.
 513
 514   .. versionadded:: 2.6
 515
 516
 517.. function:: fchown(fd, uid, gid)
 518
 519   Change the owner and group id of the file given by *fd* to the numeric *uid*
 520   and *gid*.  To leave one of the ids unchanged, set it to -1.
 521   Availability: Unix.
 522
 523   .. versionadded:: 2.6
 524
 525
 526.. function:: fdatasync(fd)
 527
 528   Force write of file with filedescriptor *fd* to disk. Does not force update of
 529   metadata. Availability: Unix.
 530
 531
 532.. function:: fpathconf(fd, name)
 533
 534   Return system configuration information relevant to an open file. *name*
 535   specifies the configuration value to retrieve; it may be a string which is the
 536   name of a defined system value; these names are specified in a number of
 537   standards (POSIX.1, Unix 95, Unix 98, and others).  Some platforms define
 538   additional names as well.  The names known to the host operating system are
 539   given in the ``pathconf_names`` dictionary.  For configuration variables not
 540   included in that mapping, passing an integer for *name* is also accepted.
 541   Availability: Unix.
 542
 543   If *name* is a string and is not known, :exc:`ValueError` is raised.  If a
 544   specific value for *name* is not supported by the host system, even if it is
 545   included in ``pathconf_names``, an :exc:`OSError` is raised with
 546   :const:`errno.EINVAL` for the error number.
 547
 548
 549.. function:: fstat(fd)
 550
 551   Return status for file descriptor *fd*, like :func:`stat`. Availability:
 552   Unix, Windows.
 553
 554
 555.. function:: fstatvfs(fd)
 556
 557   Return information about the filesystem containing the file associated with file
 558   descriptor *fd*, like :func:`statvfs`. Availability: Unix.
 559
 560
 561.. function:: fsync(fd)
 562
 563   Force write of file with filedescriptor *fd* to disk.  On Unix, this calls the
 564   native :cfunc:`fsync` function; on Windows, the MS :cfunc:`_commit` function.
 565
 566   If you're starting with a Python file object *f*, first do ``f.flush()``, and
 567   then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated
 568   with *f* are written to disk. Availability: Unix, and Windows
 569   starting in 2.2.3.
 570
 571
 572.. function:: ftruncate(fd, length)
 573
 574   Truncate the file corresponding to file descriptor *fd*, so that it is at most
 575   *length* bytes in size. Availability: Unix.
 576
 577
 578.. function:: isatty(fd)
 579
 580   Return ``True`` if the file descriptor *fd* is open and connected to a
 581   tty(-like) device, else ``False``. Availability: Unix.
 582
 583
 584.. function:: lseek(fd, pos, how)
 585
 586   Set the current position of file descriptor *fd* to position *pos*, modified
 587   by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the
 588   beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the
 589   current position; :const:`os.SEEK_END` or ``2`` to set it relative to the end of
 590   the file. Availability: Unix, Windows.
 591
 592
 593.. function:: open(file, flags[, mode])
 594
 595   Open the file *file* and set various flags according to *flags* and possibly its
 596   mode according to *mode*. The default *mode* is ``0777`` (octal), and the
 597   current umask value is first masked out.  Return the file descriptor for the
 598   newly opened file. Availability: Unix, Windows.
 599
 600   For a description of the flag and mode values, see the C run-time documentation;
 601   flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
 602   this module too (see below).
 603
 604   .. note::
 605
 606      This function is intended for low-level I/O.  For normal usage, use the built-in
 607      function :func:`open`, which returns a "file object" with :meth:`~file.read` and
 608      :meth:`~file.write` methods (and many more).  To wrap a file descriptor in a "file
 609      object", use :func:`fdopen`.
 610
 611
 612.. function:: openpty()
 613
 614   .. index:: module: pty
 615
 616   Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master,
 617   slave)`` for the pty and the tty, respectively. For a (slightly) more portable
 618   approach, use the :mod:`pty` module. Availability: some flavors of
 619   Unix.
 620
 621
 622.. function:: pipe()
 623
 624   Create a pipe.  Return a pair of file descriptors ``(r, w)`` usable for reading
 625   and writing, respectively. Availability: Unix, Windows.
 626
 627
 628.. function:: read(fd, n)
 629
 630   Read at most *n* bytes from file descriptor *fd*. Return a string containing the
 631   bytes read.  If the end of the file referred to by *fd* has been reached, an
 632   empty string is returned. Availability: Unix, Windows.
 633
 634   .. note::
 635
 636      This function is intended for low-level I/O and must be applied to a file
 637      descriptor as returned by :func:`os.open` or :func:`pipe`.  To read a "file object"
 638      returned by the built-in function :func:`open` or by :func:`popen` or
 639      :func:`fdopen`, or :data:`sys.stdin`, use its :meth:`~file.read` or
 640      :meth:`~file.readline` methods.
 641
 642
 643.. function:: tcgetpgrp(fd)
 644
 645   Return the process group associated with the terminal given by *fd* (an open
 646   file descriptor as returned by :func:`os.open`). Availability: Unix.
 647
 648
 649.. function:: tcsetpgrp(fd, pg)
 650
 651   Set the process group associated with the terminal given by *fd* (an open file
 652   descriptor as returned by :func:`os.open`) to *pg*. Availability: Unix.
 653
 654
 655.. function:: ttyname(fd)
 656
 657   Return a string which specifies the terminal device associated with
 658   file descriptor *fd*.  If *fd* is not associated with a terminal device, an
 659   exception is raised. Availability: Unix.
 660
 661
 662.. function:: write(fd, str)
 663
 664   Write the string *str* to file descriptor *fd*. Return the number of bytes
 665   actually written. Availability: Unix, Windows.
 666
 667   .. note::
 668
 669      This function is intended for low-level I/O and must be applied to a file
 670      descriptor as returned by :func:`os.open` or :func:`pipe`.  To write a "file
 671      object" returned by the built-in function :func:`open` or by :func:`popen` or
 672      :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its
 673      :meth:`~file.write` method.
 674
 675The following constants are options for the *flags* parameter to the
 676:func:`~os.open` function.  They can be combined using the bitwise OR operator
 677``|``.  Some of them are not available on all platforms.  For descriptions of
 678their availability and use, consult the :manpage:`open(2)` manual page on Unix
 679or `the MSDN <http://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>`_ on Windows.
 680
 681
 682.. data:: O_RDONLY
 683          O_WRONLY
 684          O_RDWR
 685          O_APPEND
 686          O_CREAT
 687          O_EXCL
 688          O_TRUNC
 689
 690   These constants are available on Unix and Windows.
 691
 692
 693.. data:: O_DSYNC
 694          O_RSYNC
 695          O_SYNC
 696          O_NDELAY
 697          O_NONBLOCK
 698          O_NOCTTY
 699          O_SHLOCK
 700          O_EXLOCK
 701
 702   These constants are only available on Unix.
 703
 704
 705.. data:: O_BINARY
 706          O_NOINHERIT
 707          O_SHORT_LIVED
 708          O_TEMPORARY
 709          O_RANDOM
 710          O_SEQUENTIAL
 711          O_TEXT
 712
 713   These constants are only available on Windows.
 714
 715
 716.. data:: O_ASYNC
 717          O_DIRECT
 718          O_DIRECTORY
 719          O_NOFOLLOW
 720          O_NOATIME
 721
 722   These constants are GNU extensions and not present if they are not defined by
 723   the C library.
 724
 725
 726.. data:: SEEK_SET
 727          SEEK_CUR
 728          SEEK_END
 729
 730   Parameters to the :func:`lseek` function. Their values are 0, 1, and 2,
 731   respectively. Availability: Windows, Unix.
 732
 733   .. versionadded:: 2.5
 734
 735
 736.. _os-file-dir:
 737
 738Files and Directories
 739---------------------
 740
 741.. function:: access(path, mode)
 742
 743   Use the real uid/gid to test for access to *path*.  Note that most operations
 744   will use the effective uid/gid, therefore this routine can be used in a
 745   suid/sgid environment to test if the invoking user has the specified access to
 746   *path*.  *mode* should be :const:`F_OK` to test the existence of *path*, or it
 747   can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and
 748   :const:`X_OK` to test permissions.  Return :const:`True` if access is allowed,
 749   :const:`False` if not. See the Unix man page :manpage:`access(2)` for more
 750   information. Availability: Unix, Windows.
 751
 752   .. note::
 753
 754      Using :func:`access` to check if a user is authorized to e.g. open a file before
 755      actually doing so using :func:`open` creates a security hole, because the user
 756      might exploit the short time interval  between checking and opening the file to
 757      manipulate it.
 758
 759   .. note::
 760
 761      I/O operations may fail even when :func:`access` indicates that they would
 762      succeed, particularly for operations on network filesystems which may have
 763      permissions semantics beyond the usual POSIX permission-bit model.
 764
 765
 766.. data:: F_OK
 767
 768   Value to pass as the *mode* parameter of :func:`access` to test the existence of
 769   *path*.
 770
 771
 772.. data:: R_OK
 773
 774   Value to include in the *mode* parameter of :func:`access` to test the
 775   readability of *path*.
 776
 777
 778.. data:: W_OK
 779
 780   Value to include in the *mode* parameter of :func:`access` to test the
 781   writability of *path*.
 782
 783
 784.. data:: X_OK
 785
 786   Value to include in the *mode* parameter of :func:`access` to determine if
 787   *path* can be executed.
 788
 789
 790.. function:: chdir(path)
 791
 792   .. index:: single: directory; changing
 793
 794   Change the current working directory to *path*. Availability: Unix,
 795   Windows.
 796
 797
 798.. function:: fchdir(fd)
 799
 800   Change the current working directory to the directory represented by the file
 801   descriptor *fd*.  The descriptor must refer to an opened directory, not an open
 802   file. Availability: Unix.
 803
 804   .. versionadded:: 2.3
 805
 806
 807.. function:: getcwd()
 808
 809   Return a string representing the current working directory. Availability:
 810   Unix, Windows.
 811
 812
 813.. function:: getcwdu()
 814
 815   Return a Unicode object representing the current working directory.
 816   Availability: Unix, Windows.
 817
 818   .. versionadded:: 2.3
 819
 820
 821.. function:: chflags(path, flags)
 822
 823   Set the flags of *path* to the numeric *flags*. *flags* may take a combination
 824   (bitwise OR) of the following values (as defined in the :mod:`stat` module):
 825
 826   * ``UF_NODUMP``
 827   * ``UF_IMMUTABLE``
 828   * ``UF_APPEND``
 829   * ``UF_OPAQUE``
 830   * ``UF_NOUNLINK``
 831   * ``SF_ARCHIVED``
 832   * ``SF_IMMUTABLE``
 833   * ``SF_APPEND``
 834   * ``SF_NOUNLINK``
 835   * ``SF_SNAPSHOT``
 836
 837   Availability: Unix.
 838
 839   .. versionadded:: 2.6
 840
 841
 842.. function:: chroot(path)
 843
 844   Change the root directory of the current process to *path*. Availability:
 845   Unix.
 846
 847   .. versionadded:: 2.2
 848
 849
 850.. function:: chmod(path, mode)
 851
 852   Change the mode of *path* to the numeric *mode*. *mode* may take one of the
 853   following values (as defined in the :mod:`stat` module) or bitwise ORed
 854   combinations of them:
 855
 856
 857   * :data:`stat.S_ISUID`
 858   * :data:`stat.S_ISGID`
 859   * :data:`stat.S_ENFMT`
 860   * :data:`stat.S_ISVTX`
 861   * :data:`stat.S_IREAD`
 862   * :data:`stat.S_IWRITE`
 863   * :data:`stat.S_IEXEC`
 864   * :data:`stat.S_IRWXU`
 865   * :data:`stat.S_IRUSR`
 866   * :data:`stat.S_IWUSR`
 867   * :data:`stat.S_IXUSR`
 868   * :data:`stat.S_IRWXG`
 869   * :data:`stat.S_IRGRP`
 870   * :data:`stat.S_IWGRP`
 871   * :data:`stat.S_IXGRP`
 872   * :data:`stat.S_IRWXO`
 873   * :data:`stat.S_IROTH`
 874   * :data:`stat.S_IWOTH`
 875   * :data:`stat.S_IXOTH`
 876
 877   Availability: Unix, Windows.
 878
 879   .. note::
 880
 881      Although Windows supports :func:`chmod`, you can only  set the file's read-only
 882      flag with it (via the ``stat.S_IWRITE``  and ``stat.S_IREAD``
 883      constants or a corresponding integer value).  All other bits are
 884      ignored.
 885
 886
 887.. function:: chown(path, uid, gid)
 888
 889   Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave
 890   one of the ids unchanged, set it to -1. Availability: Unix.
 891
 892
 893.. function:: lchflags(path, flags)
 894
 895   Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not
 896   follow symbolic links. Availability: Unix.
 897
 898   .. versionadded:: 2.6
 899
 900
 901.. function:: lchmod(path, mode)
 902
 903   Change the mode of *path* to the numeric *mode*. If path is a symlink, this
 904   affects the symlink rather than the target. See the docs for :func:`chmod`
 905   for possible values of *mode*.  Availability: Unix.
 906
 907   .. versionadded:: 2.6
 908
 909
 910.. function:: lchown(path, uid, gid)
 911
 912   Change the owner and group id of *path* to the numeric *uid* and *gid*. This
 913   function will not follow symbolic links. Availability: Unix.
 914
 915   .. versionadded:: 2.3
 916
 917
 918.. function:: link(src, dst)
 919
 920   Create a hard link pointing to *src* named *dst*. Availability: Unix.
 921
 922
 923.. function:: listdir(path)
 924
 925   Return a list containing the names of the entries in the directory given by
 926   *path*.  The list is in arbitrary order.  It does not include the special
 927   entries ``'.'`` and ``'..'`` even if they are present in the
 928   directory.  Availability: Unix, Windows.
 929
 930   .. versionchanged:: 2.3
 931      On Windows NT/2k/XP and Unix, if *path* is a Unicode object, the result will be
 932      a list of Unicode objects. Undecodable filenames will still be returned as
 933      string objects.
 934
 935
 936.. function:: lstat(path)
 937
 938   Like :func:`stat`, but do not follow symbolic links.  This is an alias for
 939   :func:`stat` on platforms that do not support symbolic links, such as
 940   Windows.
 941
 942
 943.. function:: mkfifo(path[, mode])
 944
 945   Create a FIFO (a named pipe) named *path* with numeric mode *mode*.  The default
 946   *mode* is ``0666`` (octal).  The current umask value is first masked out from
 947   the mode. Availability: Unix.
 948
 949   FIFOs are pipes that can be accessed like regular files.  FIFOs exist until they
 950   are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
 951   rendezvous between "client" and "server" type processes: the server opens the
 952   FIFO for reading, and the client opens it for writing.  Note that :func:`mkfifo`
 953   doesn't open the FIFO --- it just creates the rendezvous point.
 954
 955
 956.. function:: mknod(filename[, mode=0600, device])
 957
 958   Create a filesystem node (file, device special file or named pipe) named
 959   *filename*. *mode* specifies both the permissions to use and the type of node to
 960   be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
 961   ``stat.S_IFCHR``, ``stat.S_IFBLK``,
 962   and ``stat.S_IFIFO`` (those constants are available in :mod:`stat`).
 963   For ``stat.S_IFCHR`` and
 964   ``stat.S_IFBLK``, *device* defines the newly created device special file (probably using
 965   :func:`os.makedev`), otherwise it is ignored.
 966
 967   .. versionadded:: 2.3
 968
 969
 970.. function:: major(device)
 971
 972   Extract the device major number from a raw device number (usually the
 973   :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
 974
 975   .. versionadded:: 2.3
 976
 977
 978.. function:: minor(device)
 979
 980   Extract the device minor number from a raw device number (usually the
 981   :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
 982
 983   .. versionadded:: 2.3
 984
 985
 986.. function:: makedev(major, minor)
 987
 988   Compose a raw device number from the major and minor device numbers.
 989
 990   .. versionadded:: 2.3
 991
 992
 993.. function:: mkdir(path[, mode])
 994
 995   Create a directory named *path* with numeric mode *mode*. The default *mode* is
 996   ``0777`` (octal).  On some systems, *mode* is ignored.  Where it is used, the
 997   current umask value is first masked out. Availability: Unix, Windows.
 998
 999   It is also possible to create temporary directories; see the
1000   :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
1001
1002
1003.. function:: makedirs(path[, mode])
1004
1005   .. index::
1006      single: directory; creating
1007      single: UNC paths; and os.makedirs()
1008
1009   Recursive directory creation function.  Like :func:`mkdir`, but makes all
1010   intermediate-level directories needed to contain the leaf directory.  Throws an
1011   :exc:`error` exception if the leaf directory already exists or cannot be
1012   created.  The default *mode* is ``0777`` (octal).  On some systems, *mode* is
1013   ignored. Where it is used, the current umask value is first masked out.
1014
1015   .. note::
1016
1017      :func:`makedirs` will become confused if the path elements to create include
1018      :data:`os.pardir`.
1019
1020   .. versionadded:: 1.5.2
1021
1022   .. versionchanged:: 2.3
1023      This function now handles UNC paths correctly.
1024
1025
1026.. function:: pathconf(path, name)
1027
1028   Return system configuration information relevant to a named file. *name*
1029   specifies the configuration value to retrieve; it may be a string which is the
1030   name of a defined system value; these names are specified in a number of
1031   standards (POSIX.1, Unix 95, Unix 98, and others).  Some platforms define
1032   additional names as well.  The names known to the host operating system are
1033   given in the ``pathconf_names`` dictionary.  For configuration variables not
1034   included in that mapping, passing an integer for *name* is also accepted.
1035   Availability: Unix.
1036
1037   If *name* is a string and is not known, :exc:`ValueError` is raised.  If a
1038   specific value for *name* is not supported by the host system, even if it is
1039   included in ``pathconf_names``, an :exc:`OSError` is raised with
1040   :const:`errno.EINVAL` for the error number.
1041
1042
1043.. data:: pathconf_names
1044
1045   Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
1046   the integer values defined for those names by the host operating system.  This
1047   can be used to determine the set of names known to the system. Availability:
1048   Unix.
1049
1050
1051.. function:: readlink(path)
1052
1053   Return a string representing the path to which the symbolic link points.  The
1054   result may be either an absolute or relative pathname; if it is relative, it may
1055   be converted to an absolute pathname using ``os.path.join(os.path.dirname(path),
1056   result)``.
1057
1058   .. versionchanged:: 2.6
1059      If the *path* is a Unicode object the result will also be a Unicode object.
1060
1061   Availability: Unix.
1062
1063
1064.. function:: remove(path)
1065
1066   Remove the file *path*.  If *path* is a directory, :exc:`OSError` is raised; see
1067   :func:`rmdir` below to remove a directory.  This is identical to the
1068   :func:`unlink` function documented below.  On Windows, attempting to remove a
1069   file that is in use causes an exception to be raised; on Unix, the directory
1070   entry is removed but the storage allocated to the file is not made available
1071   until the original file is no longer in use. Availability: Unix,
1072   Windows.
1073
1074
1075.. function:: removedirs(path)
1076
1077   .. index:: single: directory; deleting
1078
1079   Remove directories recursively.  Works like :func:`rmdir` except that, if the
1080   leaf directory is successfully removed, :func:`removedirs`  tries to
1081   successively remove every parent directory mentioned in  *path* until an error
1082   is raised (which is ignored, because it generally means that a parent directory
1083   is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
1084   the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
1085   they are empty. Raises :exc:`OSError` if the leaf directory could not be
1086   successfully removed.
1087
1088   .. versionadded:: 1.5.2
1089
1090
1091.. function:: rename(src, dst)
1092
1093   Rename the file or directory *src* to *dst*.  If *dst* is a directory,
1094   :exc:`OSError` will be raised.  On Unix, if *dst* exists and is a file, it will
1095   be replaced silently if the user has permission.  The operation may fail on some
1096   Unix flavors if *src* and *dst* are on different filesystems.  If successful,
1097   the renaming will be an atomic operation (this is a POSIX requirement).  On
1098   Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a
1099   file; there may be no way to implement an atomic rename when *dst* names an
1100   existing file. Availability: Unix, Windows.
1101
1102
1103.. function:: renames(old, new)
1104
1105   Recursive directory or file renaming function. Works like :func:`rename`, except
1106   creation of any intermediate directories needed to make the new pathname good is
1107   attempted first. After the rename, directories corresponding to rightmost path
1108   segments of the old name will be pruned away using :func:`removedirs`.
1109
1110   .. versionadded:: 1.5.2
1111
1112   .. note::
1113
1114      This function can fail with the new directory structure made if you lack
1115      permissions needed to remove the leaf directory or file.
1116
1117
1118.. function:: rmdir(path)
1119
1120   Remove the directory *path*. Availability: Unix, Windows.
1121
1122
1123.. function:: stat(path)
1124
1125   Perform a :cfunc:`stat` system call on the given path.  The return value is an
1126   object whose attributes correspond to the members of the :ctype:`stat`
1127   structure, namely: :attr:`st_mode` (protection bits), :attr:`st_ino` (inode
1128   number), :attr:`st_dev` (device), :attr:`st_nlink` (number of hard links),
1129   :attr:`st_uid` (user id of owner), :attr:`st_gid` (group id of owner),
1130   :attr:`st_size` (size of file, in bytes), :attr:`st_atime` (time of most recent
1131   access), :attr:`st_mtime` (time of most recent content modification),
1132   :attr:`st_ctime` (platform dependent; time of most recent metadata change on
1133   Unix, or the time of creation on Windows)::
1134
1135      >>> import os
1136      >>> statinfo = os.stat('somefile.txt')
1137      >>> statinfo
1138      (33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
1139      >>> statinfo.st_size
1140      926L
1141      >>>
1142
1143   .. versionchanged:: 2.3
1144      If :func:`stat_float_times` returns ``True``, the time values are floats, measuring
1145      seconds. Fractions of a second may be reported if the system supports that. On
1146      Mac OS, the times are always floats. See :func:`stat_float_times` for further
1147      discussion.
1148
1149   On some Unix systems (such as Linux), the following attributes may also be
1150   available: :attr:`st_blocks` (number of blocks allocated for file),
1151   :attr:`st_blksize` (filesystem blocksize), :attr:`st_rdev` (type of device if an
1152   inode device). :attr:`st_flags` (user defined flags for file).
1153
1154   On other Unix systems (such as FreeBSD), the following attributes may be
1155   available (but may be only filled out if root tries to use them): :attr:`st_gen`
1156   (file generation number), :attr:`st_birthtime` (time of file creation).
1157
1158   On Mac OS systems, the following attributes may also be available:
1159   :attr:`st_rsize`, :attr:`st_creator`, :attr:`st_type`.
1160
1161   On RISCOS systems, the following attributes are also available: :attr:`st_ftype`
1162   (file type), :attr:`st_attrs` (attributes), :attr:`st_obtype` (object type).
1163
1164   .. index:: module: stat
1165
1166   For backward compatibility, the return value of :func:`stat` is also accessible
1167   as a tuple of at least 10 integers giving the most important (and portable)
1168   members of the :ctype:`stat` structure, in the order :attr:`st_mode`,
1169   :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, :attr:`st_uid`,
1170   :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, :attr:`st_mtime`,
1171   :attr:`st_ctime`. More items may be added at the end by some implementations.
1172   The standard module :mod:`stat` defines functions and constants that are useful
1173   for extracting information from a :ctype:`stat` structure. (On Windows, some
1174   items are filled with dummy values.)
1175
1176   .. note::
1177
1178      The exact meaning and resolution of the :attr:`st_atime`, :attr:`st_mtime`, and
1179      :attr:`st_ctime` members depends on the operating system and the file system.
1180      For example, on Windows systems using the FAT or FAT32 file systems,
1181      :attr:`st_mtime` has 2-second resolution, and :attr:`st_atime` has only 1-day
1182      resolution.  See your operating system documentation for details.
1183
1184   Availability: Unix, Windows.
1185
1186   .. versionchanged:: 2.2
1187      Added access to values as attributes of the returned object.
1188
1189   .. versionchanged:: 2.5
1190      Added :attr:`st_gen` and :attr:`st_birthtime`.
1191
1192
1193.. function:: stat_float_times([newvalue])
1194
1195   Determine whether :class:`stat_result` represents time stamps as float objects.
1196   If *newvalue* is ``True``, future calls to :func:`stat` return floats, if it is
1197   ``False``, future calls return ints. If *newvalue* is omitted, return the
1198   current setting.
1199
1200   For compatibility with older Python versions, accessing :class:`stat_result` as
1201   a tuple always returns integers.
1202
1203   .. versionchanged:: 2.5
1204      Python now returns float values by default. Applications which do not work
1205      correctly with floating point time stamps can use this function to restore the
1206      old behaviour.
1207
1208   The resolution of the timestamps (that is the smallest possible fraction)
1209   depends on the system. Some systems only support second resolution; on these
1210   systems, the fraction will always be zero.
1211
1212   It is recommended that this setting is only changed at program startup time in
1213   the *__main__* module; libraries should never change this setting. If an
1214   application uses a library that works incorrectly if floating point time stamps
1215   are processed, this application should turn the feature off until the library
1216   has been corrected.
1217
1218
1219.. function:: statvfs(path)
1220
1221   Perform a :cfunc:`statvfs` system call on the given path.  The return value is
1222   an object whose attributes describe the filesystem on the given path, and
1223   correspond to the members of the :ctype:`statvfs` structure, namely:
1224   :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
1225   :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
1226   :attr:`f_flag`, :attr:`f_namemax`. Availability: Unix.
1227
1228   .. index:: module: statvfs
1229
1230   For backward compatibility, the return value is also accessible as a tuple whose
1231   values correspond to the attributes, in the order given above. The standard
1232   module :mod:`statvfs` defines constants that are useful for extracting
1233   information from a :ctype:`statvfs` structure when accessing it as a sequence;
1234   this remains useful when writing code that needs to work with versions of Python
1235   that don't support accessing the fields as attributes.
1236
1237   .. versionchanged:: 2.2
1238      Added access to values as attributes of the returned object.
1239
1240
1241.. function:: symlink(src, dst)
1242
1243   Create a symbolic link pointing to *src* named *dst*. Availability: Unix.
1244
1245
1246.. function:: tempnam([dir[, prefix]])
1247
1248   Return a unique path name that is reasonable for creating a temporary file.
1249   This will be an absolute path that names a potential directory entry in the
1250   directory *dir* or a common location for temporary files if *dir* is omitted or
1251   ``None``.  If given and not ``None``, *prefix* is used to provide a short prefix
1252   to the filename.  Applications are responsible for properly creating and
1253   managing files created using paths returned by :func:`tempnam`; no automatic
1254   cleanup is provided. On Unix, the environment variable :envvar:`TMPDIR`
1255   overrides *dir*, while on Windows :envvar:`TMP` is used.  The specific
1256   behavior of this function depends on the C library implementation; some aspects
1257   are underspecified in system documentation.
1258
1259   .. warning::
1260
1261      Use of :func:`tempnam` is vulnerable to symlink attacks; consider using
1262      :func:`tmpfile` (section :ref:`os-newstreams`) instead.
1263
1264   Availability: Unix, Windows.
1265
1266
1267.. function:: tmpnam()
1268
1269   Return a unique path name that is reasonable for creating a temporary file.
1270   This will be an absolute path that names a potential directory entry in a common
1271   location for temporary files.  Applications are responsible for properly
1272   creating and managing files created using paths returned by :func:`tmpnam`; no
1273   automatic cleanup is provided.
1274
1275   .. warning::
1276
1277      Use of :func:`tmpnam` is vulnerable to symlink attacks; consider using
1278      :func:`tmpfile` (section :ref:`os-newstreams`) instead.
1279
1280   Availability: Unix, Windows.  This function probably shouldn't be used on
1281   Windows, though: Microsoft's implementation of :func:`tmpnam` always creates a
1282   name in the root directory of the current drive, and that's generally a poor
1283   location for a temp file (depending on privileges, you may not even be able to
1284   open a file using this name).
1285
1286
1287.. data:: TMP_MAX
1288
1289   The maximum number of unique names that :func:`tmpnam` will generate before
1290   reusing names.
1291
1292
1293.. function:: unlink(path)
1294
1295   Remove the file *path*.  This is the same function as :func:`remove`; the
1296   :func:`unlink` name is its traditional Unix name. Availability: Unix,
1297   Windows.
1298
1299
1300.. function:: utime(path, times)
1301
1302   Set the access and modified times of the file specified by *path*. If *times*
1303   is ``None``, then the file's access and modified times are set to the current
1304   time. (The effect is similar to running the Unix program :program:`touch` on
1305   the path.)  Otherwise, *times* must be a 2-tuple of numbers, of the form
1306   ``(atime, mtime)`` which is used to set the access and modified times,
1307   respectively. Whether a directory can be given for *path* depends on whether
1308   the operating system implements directories as files (for example, Windows
1309   does not).  Note that the exact times you set here may not be returned by a
1310   subsequent :func:`stat` call, depending on the resolution with which your
1311   operating system records access and modification times; see :func:`stat`.
1312
1313   .. versionchanged:: 2.0
1314      Added support for ``None`` for *times*.
1315
1316   Availability: Unix, Windows.
1317
1318
1319.. function:: walk(top[, topdown=True [, onerror=None[, followlinks=False]]])
1320
1321   .. index::
1322      single: directory; walking
1323      single: directory; traversal
1324
1325   Generate the file names in a directory tree by walking the tree
1326   either top-down or bottom-up. For each directory in the tree rooted at directory
1327   *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
1328   filenames)``.
1329
1330   *dirpath* is a string, the path to the directory.  *dirnames* is a list of the
1331   names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``).
1332   *filenames* is a list of the names of the non-directory files in *dirpath*.
1333   Note that the names in the lists contain no path components.  To get a full path
1334   (which begins with *top*) to a file or directory in *dirpath*, do
1335   ``os.path.join(dirpath, name)``.
1336
1337   If optional argument *topdown* is ``True`` or not specified, the triple for a
1338   directory is generated before the triples for any of its subdirectories
1339   (directories are generated top-down).  If *topdown* is ``False``, the triple for a
1340   directory is generated after the triples for all of its subdirectories
1341   (directories are generated bottom-up).
1342
1343   When *topdown* is ``True``, the caller can modify the *dirnames* list in-place
1344   (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
1345   recurse into the subdirectories whose names remain in *dirnames*; this can be
1346   used to prune the search, impose a specific order of visiting, or even to inform
1347   :func:`walk` about directories the caller creates or renames before it resumes
1348   :func:`walk` again.  Modifying *dirnames* when *topdown* is ``False`` is
1349   ineffective, because in bottom-up mode the directories in *dirnames* are
1350   generated before *dirpath* itself is generated.
1351
1352   By default errors from the :func:`listdir` call are ignored.  If optional
1353   argument *onerror* is specified, it should be a function; it will be called with
1354   one argument, an :exc:`OSError` instance.  It can report the error to continue
1355   with the walk, or raise the exception to abort the walk.  Note that the filename
1356   is available as the ``filename`` attribute of the exception object.
1357
1358   By default, :func:`walk` will not walk down into symbolic links that resolve to
1359   directories. Set *followlinks* to ``True`` to visit directories pointed to by
1360   symlinks, on systems that support them.
1361
1362   .. versionadded:: 2.6
1363      The *followlinks* parameter.
1364
1365   .. note::
1366
1367      Be aware that setting *followlinks* to ``True`` can lead to infinite recursion if a
1368      link points to a parent directory of itself. :func:`walk` does not keep track of
1369      the directories it visited already.
1370
1371   .. note::
1372
1373      If you pass a relative pathname, don't change the current working directory
1374      between resumptions of :func:`walk`.  :func:`walk` never changes the current
1375      directory, and assumes that its caller doesn't either.
1376
1377   This example displays the number of bytes taken by non-directory files in each
1378   directory under the starting directory, except that it doesn't look under any
1379   CVS subdirectory::
1380
1381      import os
1382      from os.path import join, getsize
1383      for root, dirs, files in os.walk('python/Lib/email'):
1384          print root, "consumes",
1385          print sum(getsize(join(root, name)) for name in files),
1386          print "bytes in", len(files), "non-directory files"
1387          if 'CVS' in dirs:
1388              dirs.remove('CVS')  # don't visit CVS directories
1389
1390   In the next example, walking the tree bottom-up is essential: :func:`rmdir`
1391   doesn't allow deleting a directory before the directory is empty::
1392
1393      # Delete everything reachable from the directory named in "top",
1394      # assuming there are no symbolic links.
1395      # CAUTION:  This is dangerous!  For example, if top == '/', it
1396      # could delete all your disk files.
1397      import os
1398      for root, dirs, files in os.walk(top, topdown=False):
1399          for name in files:
1400              os.remove(os.path.join(root, name))
1401          for name in dirs:
1402              os.rmdir(os.path.join(root, name))
1403
1404   .. versionadded:: 2.3
1405
1406
1407.. _os-process:
1408
1409Process Management
1410------------------
1411
1412These functions may be used to create and manage processes.
1413
1414The various :func:`exec\*` functions take a list of arguments for the new
1415program loaded into the process.  In each case, the first of these arguments is
1416passed to the new program as its own name rather than as an argument a user may
1417have typed on a command line.  For the C programmer, this is the ``argv[0]``
1418passed to a program's :cfunc:`main`.  Fo…

Large files files are truncated, but you can click here to view the full file