source: python/trunk/Doc/library/os.rst

Last change on this file was 391, checked in by dmik, 11 years ago

python: Merge vendor 2.7.6 to trunk.

  • Property svn:eol-style set to native
File size: 80.1 KB
RevLine 
[2]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
[391]16Notes on the availability of these functions:
[2]17
[391]18* The design of all built-in operating system dependent modules of Python is
19 such that as long as the same functionality is available, it uses the same
20 interface; for example, the function ``os.stat(path)`` returns stat
21 information about *path* in the same format (which happens to have originated
22 with the POSIX interface).
[2]23
[391]24* Extensions peculiar to a particular operating system are also available
25 through the :mod:`os` module, but using them is of course a threat to
26 portability.
[2]27
[391]28* An "Availability: Unix" note means that this function is commonly found on
29 Unix systems. It does not make any claims about its existence on a specific
30 operating system.
[2]31
[391]32* If not separately noted, all functions that claim "Availability: Unix" are
33 supported on Mac OS X, which builds on a Unix core.
34
35.. Availability notes get their own line and occur at the end of the function
36.. documentation.
37
[2]38.. note::
39
40 All functions in this module raise :exc:`OSError` in the case of invalid or
41 inaccessible file names and paths, or other arguments that have the correct
42 type, but are not accepted by the operating system.
43
44
45.. exception:: error
46
47 An alias for the built-in :exc:`OSError` exception.
48
49
50.. data:: name
51
[391]52 The name of the operating system dependent module imported. The following
53 names have currently been registered: ``'posix'``, ``'nt'``,
54 ``'os2'``, ``'ce'``, ``'java'``, ``'riscos'``.
[2]55
[391]56 .. seealso::
57 :attr:`sys.platform` has a finer granularity. :func:`os.uname` gives
58 system-dependent version information.
[2]59
[391]60 The :mod:`platform` module provides detailed checks for the
61 system's identity.
62
63
[2]64.. _os-procinfo:
65
66Process Parameters
67------------------
68
69These functions and data items provide information and operate on the current
70process and user.
71
72
73.. data:: environ
74
[391]75 A :term:`mapping` object representing the string environment. For example,
[2]76 ``environ['HOME']`` is the pathname of your home directory (on some platforms),
77 and is equivalent to ``getenv("HOME")`` in C.
78
79 This mapping is captured the first time the :mod:`os` module is imported,
80 typically during Python startup as part of processing :file:`site.py`. Changes
81 to the environment made after this time are not reflected in ``os.environ``,
82 except for changes made by modifying ``os.environ`` directly.
83
84 If the platform supports the :func:`putenv` function, this mapping may be used
85 to modify the environment as well as query the environment. :func:`putenv` will
86 be called automatically when the mapping is modified.
87
88 .. note::
89
90 Calling :func:`putenv` directly does not change ``os.environ``, so it's better
91 to modify ``os.environ``.
92
93 .. note::
94
95 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
96 cause memory leaks. Refer to the system documentation for
[391]97 :c:func:`putenv`.
[2]98
99 If :func:`putenv` is not provided, a modified copy of this mapping may be
100 passed to the appropriate process-creation functions to cause child processes
101 to use a modified environment.
102
103 If the platform supports the :func:`unsetenv` function, you can delete items in
104 this mapping to unset environment variables. :func:`unsetenv` will be called
105 automatically when an item is deleted from ``os.environ``, and when
106 one of the :meth:`pop` or :meth:`clear` methods is called.
107
108 .. versionchanged:: 2.6
109 Also unset environment variables when calling :meth:`os.environ.clear`
110 and :meth:`os.environ.pop`.
111
112
113.. function:: chdir(path)
114 fchdir(fd)
115 getcwd()
116 :noindex:
117
118 These functions are described in :ref:`os-file-dir`.
119
120
121.. function:: ctermid()
122
123 Return the filename corresponding to the controlling terminal of the process.
[391]124
[2]125 Availability: Unix.
126
127
128.. function:: getegid()
129
130 Return the effective group id of the current process. This corresponds to the
[391]131 "set id" bit on the file being executed in the current process.
[2]132
[391]133 Availability: Unix.
[2]134
[391]135
[2]136.. function:: geteuid()
137
138 .. index:: single: user; effective id
139
[391]140 Return the current process's effective user id.
[2]141
[391]142 Availability: Unix.
[2]143
[391]144
[2]145.. function:: getgid()
146
147 .. index:: single: process; group
148
[391]149 Return the real group id of the current process.
[2]150
[391]151 Availability: Unix.
[2]152
[391]153
[2]154.. function:: getgroups()
155
156 Return list of supplemental group ids associated with the current process.
[391]157
[2]158 Availability: Unix.
159
[391]160 .. note:: On Mac OS X, :func:`getgroups` behavior differs somewhat from
161 other Unix platforms. If the Python interpreter was built with a
162 deployment target of :const:`10.5` or earlier, :func:`getgroups` returns
163 the list of effective group ids associated with the current user process;
164 this list is limited to a system-defined number of entries, typically 16,
165 and may be modified by calls to :func:`setgroups` if suitably privileged.
166 If built with a deployment target greater than :const:`10.5`,
167 :func:`getgroups` returns the current group access list for the user
168 associated with the effective user id of the process; the group access
169 list may change over the lifetime of the process, it is not affected by
170 calls to :func:`setgroups`, and its length is not limited to 16. The
171 deployment target value, :const:`MACOSX_DEPLOYMENT_TARGET`, can be
172 obtained with :func:`sysconfig.get_config_var`.
[2]173
[391]174
175.. function:: initgroups(username, gid)
176
177 Call the system initgroups() to initialize the group access list with all of
178 the groups of which the specified username is a member, plus the specified
179 group id.
180
181 Availability: Unix.
182
183 .. versionadded:: 2.7
184
185
[2]186.. function:: getlogin()
187
188 Return the name of the user logged in on the controlling terminal of the
189 process. For most purposes, it is more useful to use the environment variable
190 :envvar:`LOGNAME` to find out who the user is, or
191 ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the currently
[391]192 effective user id.
[2]193
[391]194 Availability: Unix.
[2]195
[391]196
[2]197.. function:: getpgid(pid)
198
199 Return the process group id of the process with process id *pid*. If *pid* is 0,
[391]200 the process group id of the current process is returned.
[2]201
[391]202 Availability: Unix.
203
[2]204 .. versionadded:: 2.3
205
206
207.. function:: getpgrp()
208
209 .. index:: single: process; group
210
[391]211 Return the id of the current process group.
[2]212
[391]213 Availability: Unix.
[2]214
[391]215
[2]216.. function:: getpid()
217
218 .. index:: single: process; id
219
[391]220 Return the current process id.
[2]221
[391]222 Availability: Unix, Windows.
[2]223
[391]224
[2]225.. function:: getppid()
226
227 .. index:: single: process; id of parent
228
[391]229 Return the parent's process id.
[2]230
[391]231 Availability: Unix.
[2]232
[391]233
234.. function:: getresuid()
235
236 Return a tuple (ruid, euid, suid) denoting the current process's
237 real, effective, and saved user ids.
238
239 Availability: Unix.
240
241 .. versionadded:: 2.7
242
243
244.. function:: getresgid()
245
246 Return a tuple (rgid, egid, sgid) denoting the current process's
247 real, effective, and saved group ids.
248
249 Availability: Unix.
250
251 .. versionadded:: 2.7
252
253
[2]254.. function:: getuid()
255
256 .. index:: single: user; id
257
[391]258 Return the current process's user id.
[2]259
[391]260 Availability: Unix.
[2]261
[391]262
[2]263.. function:: getenv(varname[, value])
264
265 Return the value of the environment variable *varname* if it exists, or *value*
[391]266 if it doesn't. *value* defaults to ``None``.
[2]267
[391]268 Availability: most flavors of Unix, Windows.
[2]269
[391]270
[2]271.. function:: putenv(varname, value)
272
273 .. index:: single: environment variables; setting
274
275 Set the environment variable named *varname* to the string *value*. Such
276 changes to the environment affect subprocesses started with :func:`os.system`,
[391]277 :func:`popen` or :func:`fork` and :func:`execv`.
[2]278
[391]279 Availability: most flavors of Unix, Windows.
280
[2]281 .. note::
282
283 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
284 cause memory leaks. Refer to the system documentation for putenv.
285
286 When :func:`putenv` is supported, assignments to items in ``os.environ`` are
287 automatically translated into corresponding calls to :func:`putenv`; however,
288 calls to :func:`putenv` don't update ``os.environ``, so it is actually
289 preferable to assign to items of ``os.environ``.
290
291
292.. function:: setegid(egid)
293
[391]294 Set the current process's effective group id.
[2]295
[391]296 Availability: Unix.
[2]297
[391]298
[2]299.. function:: seteuid(euid)
300
[391]301 Set the current process's effective user id.
[2]302
[391]303 Availability: Unix.
[2]304
[391]305
[2]306.. function:: setgid(gid)
307
[391]308 Set the current process' group id.
[2]309
[391]310 Availability: Unix.
[2]311
[391]312
[2]313.. function:: setgroups(groups)
314
315 Set the list of supplemental group ids associated with the current process to
316 *groups*. *groups* must be a sequence, and each element must be an integer
317 identifying a group. This operation is typically available only to the superuser.
[391]318
[2]319 Availability: Unix.
320
321 .. versionadded:: 2.2
322
[391]323 .. note:: On Mac OS X, the length of *groups* may not exceed the
324 system-defined maximum number of effective group ids, typically 16.
325 See the documentation for :func:`getgroups` for cases where it may not
326 return the same group list set by calling setgroups().
[2]327
328.. function:: setpgrp()
329
[391]330 Call the system call :c:func:`setpgrp` or :c:func:`setpgrp(0, 0)` depending on
[2]331 which version is implemented (if any). See the Unix manual for the semantics.
[391]332
[2]333 Availability: Unix.
334
335
336.. function:: setpgid(pid, pgrp)
337
[391]338 Call the system call :c:func:`setpgid` to set the process group id of the
[2]339 process with id *pid* to the process group with id *pgrp*. See the Unix manual
[391]340 for the semantics.
[2]341
[391]342 Availability: Unix.
[2]343
344
[391]345.. function:: setregid(rgid, egid)
[2]346
[391]347 Set the current process's real and effective group ids.
[2]348
[391]349 Availability: Unix.
[2]350
351
[391]352.. function:: setresgid(rgid, egid, sgid)
[2]353
[391]354 Set the current process's real, effective, and saved group ids.
355
356 Availability: Unix.
357
358 .. versionadded:: 2.7
359
360
361.. function:: setresuid(ruid, euid, suid)
362
363 Set the current process's real, effective, and saved user ids.
364
365 Availability: Unix.
366
367 .. versionadded:: 2.7
368
369
370.. function:: setreuid(ruid, euid)
371
372 Set the current process's real and effective user ids.
373
374 Availability: Unix.
375
376
[2]377.. function:: getsid(pid)
378
[391]379 Call the system call :c:func:`getsid`. See the Unix manual for the semantics.
380
[2]381 Availability: Unix.
382
383 .. versionadded:: 2.4
384
385
386.. function:: setsid()
387
[391]388 Call the system call :c:func:`setsid`. See the Unix manual for the semantics.
389
[2]390 Availability: Unix.
391
392
393.. function:: setuid(uid)
394
395 .. index:: single: user; id, setting
396
[391]397 Set the current process's user id.
[2]398
[391]399 Availability: Unix.
[2]400
[391]401
[2]402.. placed in this section since it relates to errno.... a little weak
403.. function:: strerror(code)
404
405 Return the error message corresponding to the error code in *code*.
[391]406 On platforms where :c:func:`strerror` returns ``NULL`` when given an unknown
407 error number, :exc:`ValueError` is raised.
[2]408
[391]409 Availability: Unix, Windows.
[2]410
[391]411
[2]412.. function:: umask(mask)
413
[391]414 Set the current numeric umask and return the previous umask.
[2]415
[391]416 Availability: Unix, Windows.
[2]417
[391]418
[2]419.. function:: uname()
420
421 .. index::
422 single: gethostname() (in module socket)
423 single: gethostbyaddr() (in module socket)
424
425 Return a 5-tuple containing information identifying the current operating
426 system. The tuple contains 5 strings: ``(sysname, nodename, release, version,
427 machine)``. Some systems truncate the nodename to 8 characters or to the
428 leading component; a better way to get the hostname is
429 :func:`socket.gethostname` or even
[391]430 ``socket.gethostbyaddr(socket.gethostname())``.
[2]431
[391]432 Availability: recent flavors of Unix.
[2]433
[391]434
[2]435.. function:: unsetenv(varname)
436
437 .. index:: single: environment variables; deleting
438
439 Unset (delete) the environment variable named *varname*. Such changes to the
440 environment affect subprocesses started with :func:`os.system`, :func:`popen` or
[391]441 :func:`fork` and :func:`execv`.
[2]442
443 When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is
444 automatically translated into a corresponding call to :func:`unsetenv`; however,
445 calls to :func:`unsetenv` don't update ``os.environ``, so it is actually
446 preferable to delete items of ``os.environ``.
447
[391]448 Availability: most flavors of Unix, Windows.
[2]449
[391]450
[2]451.. _os-newstreams:
452
453File Object Creation
454--------------------
455
456These functions create new file objects. (See also :func:`open`.)
457
458
459.. function:: fdopen(fd[, mode[, bufsize]])
460
461 .. index:: single: I/O control; buffering
462
463 Return an open file object connected to the file descriptor *fd*. The *mode*
464 and *bufsize* arguments have the same meaning as the corresponding arguments to
[391]465 the built-in :func:`open` function.
[2]466
[391]467 Availability: Unix, Windows.
468
[2]469 .. versionchanged:: 2.3
470 When specified, the *mode* argument must now start with one of the letters
471 ``'r'``, ``'w'``, or ``'a'``, otherwise a :exc:`ValueError` is raised.
472
473 .. versionchanged:: 2.5
474 On Unix, when the *mode* argument starts with ``'a'``, the *O_APPEND* flag is
[391]475 set on the file descriptor (which the :c:func:`fdopen` implementation already
[2]476 does on most platforms).
477
478
479.. function:: popen(command[, mode[, bufsize]])
480
481 Open a pipe to or from *command*. The return value is an open file object
482 connected to the pipe, which can be read or written depending on whether *mode*
483 is ``'r'`` (default) or ``'w'``. The *bufsize* argument has the same meaning as
484 the corresponding argument to the built-in :func:`open` function. The exit
485 status of the command (encoded in the format specified for :func:`wait`) is
486 available as the return value of the :meth:`~file.close` method of the file object,
487 except that when the exit status is zero (termination without errors), ``None``
[391]488 is returned.
[2]489
[391]490 Availability: Unix, Windows.
491
[2]492 .. deprecated:: 2.6
493 This function is obsolete. Use the :mod:`subprocess` module. Check
494 especially the :ref:`subprocess-replacements` section.
495
496 .. versionchanged:: 2.0
497 This function worked unreliably under Windows in earlier versions of Python.
[391]498 This was due to the use of the :c:func:`_popen` function from the libraries
[2]499 provided with Windows. Newer versions of Python do not use the broken
500 implementation from the Windows libraries.
501
502
503.. function:: tmpfile()
504
505 Return a new file object opened in update mode (``w+b``). The file has no
506 directory entries associated with it and will be automatically deleted once
[391]507 there are no file descriptors for the file.
[2]508
[391]509 Availability: Unix, Windows.
510
[2]511There are a number of different :func:`popen\*` functions that provide slightly
512different ways to create subprocesses.
513
514.. deprecated:: 2.6
515 All of the :func:`popen\*` functions are obsolete. Use the :mod:`subprocess`
516 module.
517
518For each of the :func:`popen\*` variants, if *bufsize* is specified, it
519specifies the buffer size for the I/O pipes. *mode*, if provided, should be the
520string ``'b'`` or ``'t'``; on Windows this is needed to determine whether the
521file objects should be opened in binary or text mode. The default value for
522*mode* is ``'t'``.
523
524Also, for each of these variants, on Unix, *cmd* may be a sequence, in which
525case arguments will be passed directly to the program without shell intervention
526(as with :func:`os.spawnv`). If *cmd* is a string it will be passed to the shell
527(as with :func:`os.system`).
528
529These methods do not make it possible to retrieve the exit status from the child
530processes. The only way to control the input and output streams and also
531retrieve the return codes is to use the :mod:`subprocess` module; these are only
532available on Unix.
533
534For a discussion of possible deadlock conditions related to the use of these
535functions, see :ref:`popen2-flow-control`.
536
537
538.. function:: popen2(cmd[, mode[, bufsize]])
539
540 Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
541 child_stdout)``.
542
543 .. deprecated:: 2.6
544 This function is obsolete. Use the :mod:`subprocess` module. Check
545 especially the :ref:`subprocess-replacements` section.
546
547 Availability: Unix, Windows.
548
549 .. versionadded:: 2.0
550
551
552.. function:: popen3(cmd[, mode[, bufsize]])
553
554 Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
555 child_stdout, child_stderr)``.
556
557 .. deprecated:: 2.6
558 This function is obsolete. Use the :mod:`subprocess` module. Check
559 especially the :ref:`subprocess-replacements` section.
560
561 Availability: Unix, Windows.
562
563 .. versionadded:: 2.0
564
565
566.. function:: popen4(cmd[, mode[, bufsize]])
567
568 Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
569 child_stdout_and_stderr)``.
570
571 .. deprecated:: 2.6
572 This function is obsolete. Use the :mod:`subprocess` module. Check
573 especially the :ref:`subprocess-replacements` section.
574
575 Availability: Unix, Windows.
576
577 .. versionadded:: 2.0
578
579(Note that ``child_stdin, child_stdout, and child_stderr`` are named from the
580point of view of the child process, so *child_stdin* is the child's standard
581input.)
582
583This functionality is also available in the :mod:`popen2` module using functions
584of the same names, but the return values of those functions have a different
585order.
586
587
588.. _os-fd-ops:
589
590File Descriptor Operations
591--------------------------
592
593These functions operate on I/O streams referenced using file descriptors.
594
595File descriptors are small integers corresponding to a file that has been opened
596by the current process. For example, standard input is usually file descriptor
5970, standard output is 1, and standard error is 2. Further files opened by a
598process will then be assigned 3, 4, 5, and so forth. The name "file descriptor"
599is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
600by file descriptors.
601
[391]602The :meth:`~file.fileno` method can be used to obtain the file descriptor
603associated with a file object when required. Note that using the file
604descriptor directly will bypass the file object methods, ignoring aspects such
605as internal buffering of data.
[2]606
607.. function:: close(fd)
608
[391]609 Close file descriptor *fd*.
[2]610
[391]611 Availability: Unix, Windows.
612
[2]613 .. note::
614
615 This function is intended for low-level I/O and must be applied to a file
616 descriptor as returned by :func:`os.open` or :func:`pipe`. To close a "file
617 object" returned by the built-in function :func:`open` or by :func:`popen` or
[391]618 :func:`fdopen`, use its :meth:`~io.IOBase.close` method.
[2]619
620
621.. function:: closerange(fd_low, fd_high)
622
623 Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive),
[391]624 ignoring errors. Equivalent to::
[2]625
626 for fd in xrange(fd_low, fd_high):
627 try:
628 os.close(fd)
629 except OSError:
630 pass
631
[391]632 Availability: Unix, Windows.
633
[2]634 .. versionadded:: 2.6
635
636
637.. function:: dup(fd)
638
[391]639 Return a duplicate of file descriptor *fd*.
[2]640
[391]641 Availability: Unix, Windows.
[2]642
[391]643
[2]644.. function:: dup2(fd, fd2)
645
646 Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary.
[391]647
[2]648 Availability: Unix, Windows.
649
650
651.. function:: fchmod(fd, mode)
652
653 Change the mode of the file given by *fd* to the numeric *mode*. See the docs
[391]654 for :func:`chmod` for possible values of *mode*.
[2]655
[391]656 Availability: Unix.
657
[2]658 .. versionadded:: 2.6
659
660
661.. function:: fchown(fd, uid, gid)
662
663 Change the owner and group id of the file given by *fd* to the numeric *uid*
664 and *gid*. To leave one of the ids unchanged, set it to -1.
[391]665
[2]666 Availability: Unix.
667
668 .. versionadded:: 2.6
669
670
671.. function:: fdatasync(fd)
672
673 Force write of file with filedescriptor *fd* to disk. Does not force update of
[391]674 metadata.
[2]675
[391]676 Availability: Unix.
677
[2]678 .. note::
679 This function is not available on MacOS.
680
681
682.. function:: fpathconf(fd, name)
683
684 Return system configuration information relevant to an open file. *name*
685 specifies the configuration value to retrieve; it may be a string which is the
686 name of a defined system value; these names are specified in a number of
687 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
688 additional names as well. The names known to the host operating system are
689 given in the ``pathconf_names`` dictionary. For configuration variables not
690 included in that mapping, passing an integer for *name* is also accepted.
691
692 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
693 specific value for *name* is not supported by the host system, even if it is
694 included in ``pathconf_names``, an :exc:`OSError` is raised with
695 :const:`errno.EINVAL` for the error number.
696
[391]697 Availability: Unix.
[2]698
[391]699
[2]700.. function:: fstat(fd)
701
[391]702 Return status for file descriptor *fd*, like :func:`~os.stat`.
[2]703
[391]704 Availability: Unix, Windows.
[2]705
[391]706
[2]707.. function:: fstatvfs(fd)
708
709 Return information about the filesystem containing the file associated with file
[391]710 descriptor *fd*, like :func:`statvfs`.
[2]711
[391]712 Availability: Unix.
[2]713
[391]714
[2]715.. function:: fsync(fd)
716
717 Force write of file with filedescriptor *fd* to disk. On Unix, this calls the
[391]718 native :c:func:`fsync` function; on Windows, the MS :c:func:`_commit` function.
[2]719
720 If you're starting with a Python file object *f*, first do ``f.flush()``, and
721 then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated
[391]722 with *f* are written to disk.
[2]723
[391]724 Availability: Unix, and Windows starting in 2.2.3.
[2]725
[391]726
[2]727.. function:: ftruncate(fd, length)
728
729 Truncate the file corresponding to file descriptor *fd*, so that it is at most
[391]730 *length* bytes in size.
[2]731
[391]732 Availability: Unix.
[2]733
[391]734
[2]735.. function:: isatty(fd)
736
737 Return ``True`` if the file descriptor *fd* is open and connected to a
[391]738 tty(-like) device, else ``False``.
[2]739
740
741.. function:: lseek(fd, pos, how)
742
743 Set the current position of file descriptor *fd* to position *pos*, modified
744 by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the
745 beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the
[391]746 current position; :const:`SEEK_END` or ``2`` to set it relative to the end of
747 the file.
[2]748
[391]749 Availability: Unix, Windows.
[2]750
[391]751
752.. data:: SEEK_SET
753 SEEK_CUR
754 SEEK_END
755
756 Parameters to the :func:`lseek` function. Their values are 0, 1, and 2,
757 respectively.
758
759 Availability: Windows, Unix.
760
761 .. versionadded:: 2.5
762
763
[2]764.. function:: open(file, flags[, mode])
765
766 Open the file *file* and set various flags according to *flags* and possibly its
767 mode according to *mode*. The default *mode* is ``0777`` (octal), and the
768 current umask value is first masked out. Return the file descriptor for the
[391]769 newly opened file.
[2]770
771 For a description of the flag and mode values, see the C run-time documentation;
772 flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
[391]773 this module too (see :ref:`open-constants`). In particular, on Windows adding
774 :const:`O_BINARY` is needed to open files in binary mode.
[2]775
[391]776 Availability: Unix, Windows.
777
[2]778 .. note::
779
780 This function is intended for low-level I/O. For normal usage, use the
781 built-in function :func:`open`, which returns a "file object" with
782 :meth:`~file.read` and :meth:`~file.write` methods (and many more). To
783 wrap a file descriptor in a "file object", use :func:`fdopen`.
784
785
786.. function:: openpty()
787
788 .. index:: module: pty
789
790 Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master,
791 slave)`` for the pty and the tty, respectively. For a (slightly) more portable
[391]792 approach, use the :mod:`pty` module.
[2]793
[391]794 Availability: some flavors of Unix.
[2]795
[391]796
[2]797.. function:: pipe()
798
799 Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading
[391]800 and writing, respectively.
[2]801
[391]802 Availability: Unix, Windows.
[2]803
[391]804
[2]805.. function:: read(fd, n)
806
807 Read at most *n* bytes from file descriptor *fd*. Return a string containing the
808 bytes read. If the end of the file referred to by *fd* has been reached, an
[391]809 empty string is returned.
[2]810
[391]811 Availability: Unix, Windows.
812
[2]813 .. note::
814
815 This function is intended for low-level I/O and must be applied to a file
816 descriptor as returned by :func:`os.open` or :func:`pipe`. To read a "file object"
817 returned by the built-in function :func:`open` or by :func:`popen` or
818 :func:`fdopen`, or :data:`sys.stdin`, use its :meth:`~file.read` or
819 :meth:`~file.readline` methods.
820
821
822.. function:: tcgetpgrp(fd)
823
824 Return the process group associated with the terminal given by *fd* (an open
[391]825 file descriptor as returned by :func:`os.open`).
[2]826
[391]827 Availability: Unix.
[2]828
[391]829
[2]830.. function:: tcsetpgrp(fd, pg)
831
832 Set the process group associated with the terminal given by *fd* (an open file
[391]833 descriptor as returned by :func:`os.open`) to *pg*.
[2]834
[391]835 Availability: Unix.
[2]836
[391]837
[2]838.. function:: ttyname(fd)
839
840 Return a string which specifies the terminal device associated with
841 file descriptor *fd*. If *fd* is not associated with a terminal device, an
[391]842 exception is raised.
[2]843
[391]844 Availability: Unix.
[2]845
[391]846
[2]847.. function:: write(fd, str)
848
849 Write the string *str* to file descriptor *fd*. Return the number of bytes
[391]850 actually written.
[2]851
[391]852 Availability: Unix, Windows.
853
[2]854 .. note::
855
856 This function is intended for low-level I/O and must be applied to a file
857 descriptor as returned by :func:`os.open` or :func:`pipe`. To write a "file
858 object" returned by the built-in function :func:`open` or by :func:`popen` or
859 :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its
860 :meth:`~file.write` method.
861
[391]862
863.. _open-constants:
864
865``open()`` flag constants
866~~~~~~~~~~~~~~~~~~~~~~~~~
867
[2]868The following constants are options for the *flags* parameter to the
869:func:`~os.open` function. They can be combined using the bitwise OR operator
870``|``. Some of them are not available on all platforms. For descriptions of
871their availability and use, consult the :manpage:`open(2)` manual page on Unix
872or `the MSDN <http://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>`_ on Windows.
873
874
875.. data:: O_RDONLY
876 O_WRONLY
877 O_RDWR
878 O_APPEND
879 O_CREAT
880 O_EXCL
881 O_TRUNC
882
883 These constants are available on Unix and Windows.
884
885
886.. data:: O_DSYNC
887 O_RSYNC
888 O_SYNC
889 O_NDELAY
890 O_NONBLOCK
891 O_NOCTTY
892 O_SHLOCK
893 O_EXLOCK
894
895 These constants are only available on Unix.
896
897
898.. data:: O_BINARY
899 O_NOINHERIT
900 O_SHORT_LIVED
901 O_TEMPORARY
902 O_RANDOM
903 O_SEQUENTIAL
904 O_TEXT
905
906 These constants are only available on Windows.
907
908
909.. data:: O_ASYNC
910 O_DIRECT
911 O_DIRECTORY
912 O_NOFOLLOW
913 O_NOATIME
914
915 These constants are GNU extensions and not present if they are not defined by
916 the C library.
917
918
919.. _os-file-dir:
920
921Files and Directories
922---------------------
923
924.. function:: access(path, mode)
925
926 Use the real uid/gid to test for access to *path*. Note that most operations
927 will use the effective uid/gid, therefore this routine can be used in a
928 suid/sgid environment to test if the invoking user has the specified access to
929 *path*. *mode* should be :const:`F_OK` to test the existence of *path*, or it
930 can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and
931 :const:`X_OK` to test permissions. Return :const:`True` if access is allowed,
932 :const:`False` if not. See the Unix man page :manpage:`access(2)` for more
[391]933 information.
[2]934
[391]935 Availability: Unix, Windows.
936
[2]937 .. note::
938
939 Using :func:`access` to check if a user is authorized to e.g. open a file
940 before actually doing so using :func:`open` creates a security hole,
941 because the user might exploit the short time interval between checking
[391]942 and opening the file to manipulate it. It's preferable to use :term:`EAFP`
943 techniques. For example::
[2]944
[391]945 if os.access("myfile", os.R_OK):
946 with open("myfile") as fp:
947 return fp.read()
948 return "some default data"
949
950 is better written as::
951
952 try:
953 fp = open("myfile")
954 except IOError as e:
955 if e.errno == errno.EACCES:
956 return "some default data"
957 # Not a permission error.
958 raise
959 else:
960 with fp:
961 return fp.read()
962
[2]963 .. note::
964
965 I/O operations may fail even when :func:`access` indicates that they would
966 succeed, particularly for operations on network filesystems which may have
967 permissions semantics beyond the usual POSIX permission-bit model.
968
969
970.. data:: F_OK
971
972 Value to pass as the *mode* parameter of :func:`access` to test the existence of
973 *path*.
974
975
976.. data:: R_OK
977
978 Value to include in the *mode* parameter of :func:`access` to test the
979 readability of *path*.
980
981
982.. data:: W_OK
983
984 Value to include in the *mode* parameter of :func:`access` to test the
985 writability of *path*.
986
987
988.. data:: X_OK
989
990 Value to include in the *mode* parameter of :func:`access` to determine if
991 *path* can be executed.
992
993
994.. function:: chdir(path)
995
996 .. index:: single: directory; changing
997
[391]998 Change the current working directory to *path*.
[2]999
[391]1000 Availability: Unix, Windows.
[2]1001
[391]1002
[2]1003.. function:: fchdir(fd)
1004
1005 Change the current working directory to the directory represented by the file
1006 descriptor *fd*. The descriptor must refer to an opened directory, not an open
[391]1007 file.
[2]1008
[391]1009 Availability: Unix.
1010
[2]1011 .. versionadded:: 2.3
1012
1013
1014.. function:: getcwd()
1015
[391]1016 Return a string representing the current working directory.
[2]1017
[391]1018 Availability: Unix, Windows.
[2]1019
[391]1020
[2]1021.. function:: getcwdu()
1022
1023 Return a Unicode object representing the current working directory.
[391]1024
[2]1025 Availability: Unix, Windows.
1026
1027 .. versionadded:: 2.3
1028
1029
1030.. function:: chflags(path, flags)
1031
1032 Set the flags of *path* to the numeric *flags*. *flags* may take a combination
1033 (bitwise OR) of the following values (as defined in the :mod:`stat` module):
1034
[391]1035 * :data:`stat.UF_NODUMP`
1036 * :data:`stat.UF_IMMUTABLE`
1037 * :data:`stat.UF_APPEND`
1038 * :data:`stat.UF_OPAQUE`
1039 * :data:`stat.UF_NOUNLINK`
1040 * :data:`stat.UF_COMPRESSED`
1041 * :data:`stat.UF_HIDDEN`
1042 * :data:`stat.SF_ARCHIVED`
1043 * :data:`stat.SF_IMMUTABLE`
1044 * :data:`stat.SF_APPEND`
1045 * :data:`stat.SF_NOUNLINK`
1046 * :data:`stat.SF_SNAPSHOT`
[2]1047
1048 Availability: Unix.
1049
1050 .. versionadded:: 2.6
1051
1052
1053.. function:: chroot(path)
1054
1055 Change the root directory of the current process to *path*. Availability:
1056 Unix.
1057
1058 .. versionadded:: 2.2
1059
1060
1061.. function:: chmod(path, mode)
1062
1063 Change the mode of *path* to the numeric *mode*. *mode* may take one of the
1064 following values (as defined in the :mod:`stat` module) or bitwise ORed
1065 combinations of them:
1066
1067
1068 * :data:`stat.S_ISUID`
1069 * :data:`stat.S_ISGID`
1070 * :data:`stat.S_ENFMT`
1071 * :data:`stat.S_ISVTX`
1072 * :data:`stat.S_IREAD`
1073 * :data:`stat.S_IWRITE`
1074 * :data:`stat.S_IEXEC`
1075 * :data:`stat.S_IRWXU`
1076 * :data:`stat.S_IRUSR`
1077 * :data:`stat.S_IWUSR`
1078 * :data:`stat.S_IXUSR`
1079 * :data:`stat.S_IRWXG`
1080 * :data:`stat.S_IRGRP`
1081 * :data:`stat.S_IWGRP`
1082 * :data:`stat.S_IXGRP`
1083 * :data:`stat.S_IRWXO`
1084 * :data:`stat.S_IROTH`
1085 * :data:`stat.S_IWOTH`
1086 * :data:`stat.S_IXOTH`
1087
1088 Availability: Unix, Windows.
1089
1090 .. note::
1091
1092 Although Windows supports :func:`chmod`, you can only set the file's read-only
1093 flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD``
1094 constants or a corresponding integer value). All other bits are
1095 ignored.
1096
1097
1098.. function:: chown(path, uid, gid)
1099
1100 Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave
[391]1101 one of the ids unchanged, set it to -1.
[2]1102
[391]1103 Availability: Unix.
[2]1104
[391]1105
[2]1106.. function:: lchflags(path, flags)
1107
1108 Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not
[391]1109 follow symbolic links.
[2]1110
[391]1111 Availability: Unix.
1112
[2]1113 .. versionadded:: 2.6
1114
1115
1116.. function:: lchmod(path, mode)
1117
1118 Change the mode of *path* to the numeric *mode*. If path is a symlink, this
1119 affects the symlink rather than the target. See the docs for :func:`chmod`
[391]1120 for possible values of *mode*.
[2]1121
[391]1122 Availability: Unix.
1123
[2]1124 .. versionadded:: 2.6
1125
1126
1127.. function:: lchown(path, uid, gid)
1128
1129 Change the owner and group id of *path* to the numeric *uid* and *gid*. This
[391]1130 function will not follow symbolic links.
[2]1131
[391]1132 Availability: Unix.
1133
[2]1134 .. versionadded:: 2.3
1135
1136
1137.. function:: link(source, link_name)
1138
[391]1139 Create a hard link pointing to *source* named *link_name*.
[2]1140
[391]1141 Availability: Unix.
[2]1142
[391]1143
[2]1144.. function:: listdir(path)
1145
1146 Return a list containing the names of the entries in the directory given by
1147 *path*. The list is in arbitrary order. It does not include the special
1148 entries ``'.'`` and ``'..'`` even if they are present in the
[391]1149 directory.
[2]1150
[391]1151 Availability: Unix, Windows.
1152
[2]1153 .. versionchanged:: 2.3
1154 On Windows NT/2k/XP and Unix, if *path* is a Unicode object, the result will be
1155 a list of Unicode objects. Undecodable filenames will still be returned as
1156 string objects.
1157
1158
1159.. function:: lstat(path)
1160
[391]1161 Perform the equivalent of an :c:func:`lstat` system call on the given path.
1162 Similar to :func:`~os.stat`, but does not follow symbolic links. On
1163 platforms that do not support symbolic links, this is an alias for
1164 :func:`~os.stat`.
[2]1165
1166
1167.. function:: mkfifo(path[, mode])
1168
1169 Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The default
1170 *mode* is ``0666`` (octal). The current umask value is first masked out from
[391]1171 the mode.
[2]1172
[391]1173 Availability: Unix.
1174
[2]1175 FIFOs are pipes that can be accessed like regular files. FIFOs exist until they
1176 are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
1177 rendezvous between "client" and "server" type processes: the server opens the
1178 FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo`
1179 doesn't open the FIFO --- it just creates the rendezvous point.
1180
1181
[391]1182.. function:: mknod(filename[, mode=0600[, device=0]])
[2]1183
1184 Create a filesystem node (file, device special file or named pipe) named
1185 *filename*. *mode* specifies both the permissions to use and the type of node to
1186 be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
1187 ``stat.S_IFCHR``, ``stat.S_IFBLK``,
1188 and ``stat.S_IFIFO`` (those constants are available in :mod:`stat`).
1189 For ``stat.S_IFCHR`` and
1190 ``stat.S_IFBLK``, *device* defines the newly created device special file (probably using
1191 :func:`os.makedev`), otherwise it is ignored.
1192
1193 .. versionadded:: 2.3
1194
1195
1196.. function:: major(device)
1197
1198 Extract the device major number from a raw device number (usually the
[391]1199 :attr:`st_dev` or :attr:`st_rdev` field from :c:type:`stat`).
[2]1200
1201 .. versionadded:: 2.3
1202
1203
1204.. function:: minor(device)
1205
1206 Extract the device minor number from a raw device number (usually the
[391]1207 :attr:`st_dev` or :attr:`st_rdev` field from :c:type:`stat`).
[2]1208
1209 .. versionadded:: 2.3
1210
1211
1212.. function:: makedev(major, minor)
1213
1214 Compose a raw device number from the major and minor device numbers.
1215
1216 .. versionadded:: 2.3
1217
1218
1219.. function:: mkdir(path[, mode])
1220
1221 Create a directory named *path* with numeric mode *mode*. The default *mode* is
1222 ``0777`` (octal). On some systems, *mode* is ignored. Where it is used, the
[391]1223 current umask value is first masked out. If the directory already exists,
1224 :exc:`OSError` is raised.
[2]1225
1226 It is also possible to create temporary directories; see the
1227 :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
1228
[391]1229 Availability: Unix, Windows.
[2]1230
[391]1231
[2]1232.. function:: makedirs(path[, mode])
1233
1234 .. index::
1235 single: directory; creating
1236 single: UNC paths; and os.makedirs()
1237
1238 Recursive directory creation function. Like :func:`mkdir`, but makes all
[391]1239 intermediate-level directories needed to contain the leaf directory. Raises an
[2]1240 :exc:`error` exception if the leaf directory already exists or cannot be
1241 created. The default *mode* is ``0777`` (octal). On some systems, *mode* is
1242 ignored. Where it is used, the current umask value is first masked out.
1243
1244 .. note::
1245
1246 :func:`makedirs` will become confused if the path elements to create include
1247 :data:`os.pardir`.
1248
1249 .. versionadded:: 1.5.2
1250
1251 .. versionchanged:: 2.3
1252 This function now handles UNC paths correctly.
1253
1254
1255.. function:: pathconf(path, name)
1256
1257 Return system configuration information relevant to a named file. *name*
1258 specifies the configuration value to retrieve; it may be a string which is the
1259 name of a defined system value; these names are specified in a number of
1260 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
1261 additional names as well. The names known to the host operating system are
1262 given in the ``pathconf_names`` dictionary. For configuration variables not
1263 included in that mapping, passing an integer for *name* is also accepted.
1264
1265 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
1266 specific value for *name* is not supported by the host system, even if it is
1267 included in ``pathconf_names``, an :exc:`OSError` is raised with
1268 :const:`errno.EINVAL` for the error number.
1269
[391]1270 Availability: Unix.
[2]1271
[391]1272
[2]1273.. data:: pathconf_names
1274
1275 Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
1276 the integer values defined for those names by the host operating system. This
1277 can be used to determine the set of names known to the system. Availability:
1278 Unix.
1279
1280
1281.. function:: readlink(path)
1282
1283 Return a string representing the path to which the symbolic link points. The
1284 result may be either an absolute or relative pathname; if it is relative, it may
1285 be converted to an absolute pathname using ``os.path.join(os.path.dirname(path),
1286 result)``.
1287
1288 .. versionchanged:: 2.6
1289 If the *path* is a Unicode object the result will also be a Unicode object.
1290
1291 Availability: Unix.
1292
1293
1294.. function:: remove(path)
1295
1296 Remove (delete) the file *path*. If *path* is a directory, :exc:`OSError` is
1297 raised; see :func:`rmdir` below to remove a directory. This is identical to
1298 the :func:`unlink` function documented below. On Windows, attempting to
1299 remove a file that is in use causes an exception to be raised; on Unix, the
1300 directory entry is removed but the storage allocated to the file is not made
[391]1301 available until the original file is no longer in use.
[2]1302
[391]1303 Availability: Unix, Windows.
[2]1304
[391]1305
[2]1306.. function:: removedirs(path)
1307
1308 .. index:: single: directory; deleting
1309
1310 Remove directories recursively. Works like :func:`rmdir` except that, if the
1311 leaf directory is successfully removed, :func:`removedirs` tries to
1312 successively remove every parent directory mentioned in *path* until an error
1313 is raised (which is ignored, because it generally means that a parent directory
1314 is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
1315 the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
1316 they are empty. Raises :exc:`OSError` if the leaf directory could not be
1317 successfully removed.
1318
1319 .. versionadded:: 1.5.2
1320
1321
1322.. function:: rename(src, dst)
1323
1324 Rename the file or directory *src* to *dst*. If *dst* is a directory,
1325 :exc:`OSError` will be raised. On Unix, if *dst* exists and is a file, it will
1326 be replaced silently if the user has permission. The operation may fail on some
1327 Unix flavors if *src* and *dst* are on different filesystems. If successful,
1328 the renaming will be an atomic operation (this is a POSIX requirement). On
1329 Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a
1330 file; there may be no way to implement an atomic rename when *dst* names an
[391]1331 existing file.
[2]1332
[391]1333 Availability: Unix, Windows.
[2]1334
[391]1335
[2]1336.. function:: renames(old, new)
1337
1338 Recursive directory or file renaming function. Works like :func:`rename`, except
1339 creation of any intermediate directories needed to make the new pathname good is
1340 attempted first. After the rename, directories corresponding to rightmost path
1341 segments of the old name will be pruned away using :func:`removedirs`.
1342
1343 .. versionadded:: 1.5.2
1344
1345 .. note::
1346
1347 This function can fail with the new directory structure made if you lack
1348 permissions needed to remove the leaf directory or file.
1349
1350
1351.. function:: rmdir(path)
1352
1353 Remove (delete) the directory *path*. Only works when the directory is
1354 empty, otherwise, :exc:`OSError` is raised. In order to remove whole
[391]1355 directory trees, :func:`shutil.rmtree` can be used.
[2]1356
[391]1357 Availability: Unix, Windows.
[2]1358
[391]1359
[2]1360.. function:: stat(path)
1361
[391]1362 Perform the equivalent of a :c:func:`stat` system call on the given path.
1363 (This function follows symlinks; to stat a symlink use :func:`lstat`.)
[2]1364
[391]1365 The return value is an object whose attributes correspond to the members
1366 of the :c:type:`stat` structure, namely:
[2]1367
[391]1368 * :attr:`st_mode` - protection bits,
1369 * :attr:`st_ino` - inode number,
1370 * :attr:`st_dev` - device,
1371 * :attr:`st_nlink` - number of hard links,
1372 * :attr:`st_uid` - user id of owner,
1373 * :attr:`st_gid` - group id of owner,
1374 * :attr:`st_size` - size of file, in bytes,
1375 * :attr:`st_atime` - time of most recent access,
1376 * :attr:`st_mtime` - time of most recent content modification,
1377 * :attr:`st_ctime` - platform dependent; time of most recent metadata change on
1378 Unix, or the time of creation on Windows)
1379
[2]1380 .. versionchanged:: 2.3
1381 If :func:`stat_float_times` returns ``True``, the time values are floats, measuring
1382 seconds. Fractions of a second may be reported if the system supports that. On
1383 Mac OS, the times are always floats. See :func:`stat_float_times` for further
1384 discussion.
1385
1386 On some Unix systems (such as Linux), the following attributes may also be
[391]1387 available:
[2]1388
[391]1389 * :attr:`st_blocks` - number of 512-byte blocks allocated for file
1390 * :attr:`st_blksize` - filesystem blocksize for efficient file system I/O
1391 * :attr:`st_rdev` - type of device if an inode device
1392 * :attr:`st_flags` - user defined flags for file
1393
[2]1394 On other Unix systems (such as FreeBSD), the following attributes may be
[391]1395 available (but may be only filled out if root tries to use them):
[2]1396
[391]1397 * :attr:`st_gen` - file generation number
1398 * :attr:`st_birthtime` - time of file creation
1399
[2]1400 On Mac OS systems, the following attributes may also be available:
1401
[391]1402 * :attr:`st_rsize`
1403 * :attr:`st_creator`
1404 * :attr:`st_type`
[2]1405
[391]1406 On RISCOS systems, the following attributes are also available:
[2]1407
[391]1408 * :attr:`st_ftype` (file type)
1409 * :attr:`st_attrs` (attributes)
1410 * :attr:`st_obtype` (object type).
1411
1412 .. note::
1413
1414 The exact meaning and resolution of the :attr:`st_atime`,
1415 :attr:`st_mtime`, and :attr:`st_ctime` attributes depend on the operating
1416 system and the file system. For example, on Windows systems using the FAT
1417 or FAT32 file systems, :attr:`st_mtime` has 2-second resolution, and
1418 :attr:`st_atime` has only 1-day resolution. See your operating system
1419 documentation for details.
1420
1421 For backward compatibility, the return value of :func:`~os.stat` is also accessible
[2]1422 as a tuple of at least 10 integers giving the most important (and portable)
[391]1423 members of the :c:type:`stat` structure, in the order :attr:`st_mode`,
[2]1424 :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, :attr:`st_uid`,
1425 :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, :attr:`st_mtime`,
1426 :attr:`st_ctime`. More items may be added at the end by some implementations.
[391]1427
1428 .. index:: module: stat
1429
[2]1430 The standard module :mod:`stat` defines functions and constants that are useful
[391]1431 for extracting information from a :c:type:`stat` structure. (On Windows, some
[2]1432 items are filled with dummy values.)
1433
[391]1434 Example::
[2]1435
[391]1436 >>> import os
1437 >>> statinfo = os.stat('somefile.txt')
1438 >>> statinfo
1439 (33188, 422511, 769, 1, 1032, 100, 926, 1105022698,1105022732, 1105022732)
1440 >>> statinfo.st_size
1441 926
[2]1442
1443 Availability: Unix, Windows.
1444
1445 .. versionchanged:: 2.2
1446 Added access to values as attributes of the returned object.
1447
1448 .. versionchanged:: 2.5
1449 Added :attr:`st_gen` and :attr:`st_birthtime`.
1450
1451
1452.. function:: stat_float_times([newvalue])
1453
1454 Determine whether :class:`stat_result` represents time stamps as float objects.
[391]1455 If *newvalue* is ``True``, future calls to :func:`~os.stat` return floats, if it is
[2]1456 ``False``, future calls return ints. If *newvalue* is omitted, return the
1457 current setting.
1458
1459 For compatibility with older Python versions, accessing :class:`stat_result` as
1460 a tuple always returns integers.
1461
1462 .. versionchanged:: 2.5
1463 Python now returns float values by default. Applications which do not work
1464 correctly with floating point time stamps can use this function to restore the
1465 old behaviour.
1466
1467 The resolution of the timestamps (that is the smallest possible fraction)
1468 depends on the system. Some systems only support second resolution; on these
1469 systems, the fraction will always be zero.
1470
1471 It is recommended that this setting is only changed at program startup time in
1472 the *__main__* module; libraries should never change this setting. If an
1473 application uses a library that works incorrectly if floating point time stamps
1474 are processed, this application should turn the feature off until the library
1475 has been corrected.
1476
1477
1478.. function:: statvfs(path)
1479
[391]1480 Perform a :c:func:`statvfs` system call on the given path. The return value is
[2]1481 an object whose attributes describe the filesystem on the given path, and
[391]1482 correspond to the members of the :c:type:`statvfs` structure, namely:
[2]1483 :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
1484 :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
[391]1485 :attr:`f_flag`, :attr:`f_namemax`.
[2]1486
1487 .. index:: module: statvfs
1488
1489 For backward compatibility, the return value is also accessible as a tuple whose
1490 values correspond to the attributes, in the order given above. The standard
1491 module :mod:`statvfs` defines constants that are useful for extracting
[391]1492 information from a :c:type:`statvfs` structure when accessing it as a sequence;
[2]1493 this remains useful when writing code that needs to work with versions of Python
1494 that don't support accessing the fields as attributes.
1495
[391]1496 Availability: Unix.
1497
[2]1498 .. versionchanged:: 2.2
1499 Added access to values as attributes of the returned object.
1500
1501
1502.. function:: symlink(source, link_name)
1503
[391]1504 Create a symbolic link pointing to *source* named *link_name*.
[2]1505
[391]1506 Availability: Unix.
[2]1507
[391]1508
[2]1509.. function:: tempnam([dir[, prefix]])
1510
1511 Return a unique path name that is reasonable for creating a temporary file.
1512 This will be an absolute path that names a potential directory entry in the
1513 directory *dir* or a common location for temporary files if *dir* is omitted or
1514 ``None``. If given and not ``None``, *prefix* is used to provide a short prefix
1515 to the filename. Applications are responsible for properly creating and
1516 managing files created using paths returned by :func:`tempnam`; no automatic
1517 cleanup is provided. On Unix, the environment variable :envvar:`TMPDIR`
1518 overrides *dir*, while on Windows :envvar:`TMP` is used. The specific
1519 behavior of this function depends on the C library implementation; some aspects
1520 are underspecified in system documentation.
1521
1522 .. warning::
1523
1524 Use of :func:`tempnam` is vulnerable to symlink attacks; consider using
1525 :func:`tmpfile` (section :ref:`os-newstreams`) instead.
1526
1527 Availability: Unix, Windows.
1528
1529
1530.. function:: tmpnam()
1531
1532 Return a unique path name that is reasonable for creating a temporary file.
1533 This will be an absolute path that names a potential directory entry in a common
1534 location for temporary files. Applications are responsible for properly
1535 creating and managing files created using paths returned by :func:`tmpnam`; no
1536 automatic cleanup is provided.
1537
1538 .. warning::
1539
1540 Use of :func:`tmpnam` is vulnerable to symlink attacks; consider using
1541 :func:`tmpfile` (section :ref:`os-newstreams`) instead.
1542
1543 Availability: Unix, Windows. This function probably shouldn't be used on
1544 Windows, though: Microsoft's implementation of :func:`tmpnam` always creates a
1545 name in the root directory of the current drive, and that's generally a poor
1546 location for a temp file (depending on privileges, you may not even be able to
1547 open a file using this name).
1548
1549
1550.. data:: TMP_MAX
1551
1552 The maximum number of unique names that :func:`tmpnam` will generate before
1553 reusing names.
1554
1555
1556.. function:: unlink(path)
1557
1558 Remove (delete) the file *path*. This is the same function as
1559 :func:`remove`; the :func:`unlink` name is its traditional Unix
[391]1560 name.
[2]1561
[391]1562 Availability: Unix, Windows.
[2]1563
[391]1564
[2]1565.. function:: utime(path, times)
1566
1567 Set the access and modified times of the file specified by *path*. If *times*
1568 is ``None``, then the file's access and modified times are set to the current
1569 time. (The effect is similar to running the Unix program :program:`touch` on
1570 the path.) Otherwise, *times* must be a 2-tuple of numbers, of the form
1571 ``(atime, mtime)`` which is used to set the access and modified times,
1572 respectively. Whether a directory can be given for *path* depends on whether
1573 the operating system implements directories as files (for example, Windows
1574 does not). Note that the exact times you set here may not be returned by a
[391]1575 subsequent :func:`~os.stat` call, depending on the resolution with which your
1576 operating system records access and modification times; see :func:`~os.stat`.
[2]1577
1578 .. versionchanged:: 2.0
1579 Added support for ``None`` for *times*.
1580
1581 Availability: Unix, Windows.
1582
1583
[391]1584.. function:: walk(top, topdown=True, onerror=None, followlinks=False)
[2]1585
1586 .. index::
1587 single: directory; walking
1588 single: directory; traversal
1589
1590 Generate the file names in a directory tree by walking the tree
1591 either top-down or bottom-up. For each directory in the tree rooted at directory
1592 *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
1593 filenames)``.
1594
1595 *dirpath* is a string, the path to the directory. *dirnames* is a list of the
1596 names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``).
1597 *filenames* is a list of the names of the non-directory files in *dirpath*.
1598 Note that the names in the lists contain no path components. To get a full path
1599 (which begins with *top*) to a file or directory in *dirpath*, do
1600 ``os.path.join(dirpath, name)``.
1601
1602 If optional argument *topdown* is ``True`` or not specified, the triple for a
1603 directory is generated before the triples for any of its subdirectories
1604 (directories are generated top-down). If *topdown* is ``False``, the triple for a
1605 directory is generated after the triples for all of its subdirectories
1606 (directories are generated bottom-up).
1607
1608 When *topdown* is ``True``, the caller can modify the *dirnames* list in-place
1609 (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
1610 recurse into the subdirectories whose names remain in *dirnames*; this can be
1611 used to prune the search, impose a specific order of visiting, or even to inform
1612 :func:`walk` about directories the caller creates or renames before it resumes
1613 :func:`walk` again. Modifying *dirnames* when *topdown* is ``False`` is
1614 ineffective, because in bottom-up mode the directories in *dirnames* are
1615 generated before *dirpath* itself is generated.
1616
[391]1617 By default, errors from the :func:`listdir` call are ignored. If optional
[2]1618 argument *onerror* is specified, it should be a function; it will be called with
1619 one argument, an :exc:`OSError` instance. It can report the error to continue
1620 with the walk, or raise the exception to abort the walk. Note that the filename
1621 is available as the ``filename`` attribute of the exception object.
1622
1623 By default, :func:`walk` will not walk down into symbolic links that resolve to
1624 directories. Set *followlinks* to ``True`` to visit directories pointed to by
1625 symlinks, on systems that support them.
1626
1627 .. versionadded:: 2.6
1628 The *followlinks* parameter.
1629
1630 .. note::
1631
1632 Be aware that setting *followlinks* to ``True`` can lead to infinite recursion if a
1633 link points to a parent directory of itself. :func:`walk` does not keep track of
1634 the directories it visited already.
1635
1636 .. note::
1637
1638 If you pass a relative pathname, don't change the current working directory
1639 between resumptions of :func:`walk`. :func:`walk` never changes the current
1640 directory, and assumes that its caller doesn't either.
1641
1642 This example displays the number of bytes taken by non-directory files in each
1643 directory under the starting directory, except that it doesn't look under any
1644 CVS subdirectory::
1645
1646 import os
1647 from os.path import join, getsize
1648 for root, dirs, files in os.walk('python/Lib/email'):
1649 print root, "consumes",
1650 print sum(getsize(join(root, name)) for name in files),
1651 print "bytes in", len(files), "non-directory files"
1652 if 'CVS' in dirs:
1653 dirs.remove('CVS') # don't visit CVS directories
1654
1655 In the next example, walking the tree bottom-up is essential: :func:`rmdir`
1656 doesn't allow deleting a directory before the directory is empty::
1657
1658 # Delete everything reachable from the directory named in "top",
1659 # assuming there are no symbolic links.
1660 # CAUTION: This is dangerous! For example, if top == '/', it
1661 # could delete all your disk files.
1662 import os
1663 for root, dirs, files in os.walk(top, topdown=False):
1664 for name in files:
1665 os.remove(os.path.join(root, name))
1666 for name in dirs:
1667 os.rmdir(os.path.join(root, name))
1668
1669 .. versionadded:: 2.3
1670
1671
1672.. _os-process:
1673
1674Process Management
1675------------------
1676
1677These functions may be used to create and manage processes.
1678
[391]1679The various :func:`exec\* <execl>` functions take a list of arguments for the new
[2]1680program loaded into the process. In each case, the first of these arguments is
1681passed to the new program as its own name rather than as an argument a user may
1682have typed on a command line. For the C programmer, this is the ``argv[0]``
[391]1683passed to a program's :c:func:`main`. For example, ``os.execv('/bin/echo',
[2]1684['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
1685to be ignored.
1686
1687
1688.. function:: abort()
1689
1690 Generate a :const:`SIGABRT` signal to the current process. On Unix, the default
1691 behavior is to produce a core dump; on Windows, the process immediately returns
[391]1692 an exit code of ``3``. Be aware that calling this function will not call the
1693 Python signal handler registered for :const:`SIGABRT` with
1694 :func:`signal.signal`.
1695
[2]1696 Availability: Unix, Windows.
1697
1698
1699.. function:: execl(path, arg0, arg1, ...)
1700 execle(path, arg0, arg1, ..., env)
1701 execlp(file, arg0, arg1, ...)
1702 execlpe(file, arg0, arg1, ..., env)
1703 execv(path, args)
1704 execve(path, args, env)
1705 execvp(file, args)
1706 execvpe(file, args, env)
1707
1708 These functions all execute a new program, replacing the current process; they
1709 do not return. On Unix, the new executable is loaded into the current process,
1710 and will have the same process id as the caller. Errors will be reported as
1711 :exc:`OSError` exceptions.
1712
1713 The current process is replaced immediately. Open file objects and
1714 descriptors are not flushed, so if there may be data buffered
1715 on these open files, you should flush them using
1716 :func:`sys.stdout.flush` or :func:`os.fsync` before calling an
[391]1717 :func:`exec\* <execl>` function.
[2]1718
[391]1719 The "l" and "v" variants of the :func:`exec\* <execl>` functions differ in how
[2]1720 command-line arguments are passed. The "l" variants are perhaps the easiest
1721 to work with if the number of parameters is fixed when the code is written; the
1722 individual parameters simply become additional parameters to the :func:`execl\*`
1723 functions. The "v" variants are good when the number of parameters is
1724 variable, with the arguments being passed in a list or tuple as the *args*
1725 parameter. In either case, the arguments to the child process should start with
1726 the name of the command being run, but this is not enforced.
1727
1728 The variants which include a "p" near the end (:func:`execlp`,
1729 :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
1730 :envvar:`PATH` environment variable to locate the program *file*. When the
[391]1731 environment is being replaced (using one of the :func:`exec\*e <execl>` variants,
[2]1732 discussed in the next paragraph), the new environment is used as the source of
1733 the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
1734 :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
1735 locate the executable; *path* must contain an appropriate absolute or relative
1736 path.
1737
1738 For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
1739 that these all end in "e"), the *env* parameter must be a mapping which is
1740 used to define the environment variables for the new process (these are used
1741 instead of the current process' environment); the functions :func:`execl`,
1742 :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
1743 inherit the environment of the current process.
1744
1745 Availability: Unix, Windows.
1746
1747
1748.. function:: _exit(n)
1749
[391]1750 Exit the process with status *n*, without calling cleanup handlers, flushing
1751 stdio buffers, etc.
[2]1752
[391]1753 Availability: Unix, Windows.
1754
[2]1755 .. note::
1756
[391]1757 The standard way to exit is ``sys.exit(n)``. :func:`_exit` should
1758 normally only be used in the child process after a :func:`fork`.
[2]1759
1760The following exit codes are defined and can be used with :func:`_exit`,
1761although they are not required. These are typically used for system programs
1762written in Python, such as a mail server's external command delivery program.
1763
1764.. note::
1765
1766 Some of these may not be available on all Unix platforms, since there is some
1767 variation. These constants are defined where they are defined by the underlying
1768 platform.
1769
1770
1771.. data:: EX_OK
1772
[391]1773 Exit code that means no error occurred.
[2]1774
[391]1775 Availability: Unix.
1776
[2]1777 .. versionadded:: 2.3
1778
1779
1780.. data:: EX_USAGE
1781
1782 Exit code that means the command was used incorrectly, such as when the wrong
[391]1783 number of arguments are given.
[2]1784
[391]1785 Availability: Unix.
1786
[2]1787 .. versionadded:: 2.3
1788
1789
1790.. data:: EX_DATAERR
1791
[391]1792 Exit code that means the input data was incorrect.
[2]1793
[391]1794 Availability: Unix.
1795
[2]1796 .. versionadded:: 2.3
1797
1798
1799.. data:: EX_NOINPUT
1800
1801 Exit code that means an input file did not exist or was not readable.
[391]1802
[2]1803 Availability: Unix.
1804
1805 .. versionadded:: 2.3
1806
1807
1808.. data:: EX_NOUSER
1809
[391]1810 Exit code that means a specified user did not exist.
[2]1811
[391]1812 Availability: Unix.
1813
[2]1814 .. versionadded:: 2.3
1815
1816
1817.. data:: EX_NOHOST
1818
[391]1819 Exit code that means a specified host did not exist.
[2]1820
[391]1821 Availability: Unix.
1822
[2]1823 .. versionadded:: 2.3
1824
1825
1826.. data:: EX_UNAVAILABLE
1827
[391]1828 Exit code that means that a required service is unavailable.
[2]1829
[391]1830 Availability: Unix.
1831
[2]1832 .. versionadded:: 2.3
1833
1834
1835.. data:: EX_SOFTWARE
1836
[391]1837 Exit code that means an internal software error was detected.
[2]1838
[391]1839 Availability: Unix.
1840
[2]1841 .. versionadded:: 2.3
1842
1843
1844.. data:: EX_OSERR
1845
1846 Exit code that means an operating system error was detected, such as the
[391]1847 inability to fork or create a pipe.
[2]1848
[391]1849 Availability: Unix.
1850
[2]1851 .. versionadded:: 2.3
1852
1853
1854.. data:: EX_OSFILE
1855
1856 Exit code that means some system file did not exist, could not be opened, or had
[391]1857 some other kind of error.
[2]1858
[391]1859 Availability: Unix.
1860
[2]1861 .. versionadded:: 2.3
1862
1863
1864.. data:: EX_CANTCREAT
1865
1866 Exit code that means a user specified output file could not be created.
[391]1867
[2]1868 Availability: Unix.
1869
1870 .. versionadded:: 2.3
1871
1872
1873.. data:: EX_IOERR
1874
1875 Exit code that means that an error occurred while doing I/O on some file.
[391]1876
[2]1877 Availability: Unix.
1878
1879 .. versionadded:: 2.3
1880
1881
1882.. data:: EX_TEMPFAIL
1883
1884 Exit code that means a temporary failure occurred. This indicates something
1885 that may not really be an error, such as a network connection that couldn't be
[391]1886 made during a retryable operation.
[2]1887
[391]1888 Availability: Unix.
1889
[2]1890 .. versionadded:: 2.3
1891
1892
1893.. data:: EX_PROTOCOL
1894
1895 Exit code that means that a protocol exchange was illegal, invalid, or not
[391]1896 understood.
[2]1897
[391]1898 Availability: Unix.
1899
[2]1900 .. versionadded:: 2.3
1901
1902
1903.. data:: EX_NOPERM
1904
1905 Exit code that means that there were insufficient permissions to perform the
[391]1906 operation (but not intended for file system problems).
[2]1907
[391]1908 Availability: Unix.
1909
[2]1910 .. versionadded:: 2.3
1911
1912
1913.. data:: EX_CONFIG
1914
1915 Exit code that means that some kind of configuration error occurred.
[391]1916
[2]1917 Availability: Unix.
1918
1919 .. versionadded:: 2.3
1920
1921
1922.. data:: EX_NOTFOUND
1923
[391]1924 Exit code that means something like "an entry was not found".
[2]1925
[391]1926 Availability: Unix.
1927
[2]1928 .. versionadded:: 2.3
1929
1930
1931.. function:: fork()
1932
1933 Fork a child process. Return ``0`` in the child and the child's process id in the
1934 parent. If an error occurs :exc:`OSError` is raised.
1935
1936 Note that some platforms including FreeBSD <= 6.3, Cygwin and OS/2 EMX have
1937 known issues when using fork() from a thread.
1938
1939 Availability: Unix.
1940
1941
1942.. function:: forkpty()
1943
1944 Fork a child process, using a new pseudo-terminal as the child's controlling
1945 terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
1946 new child's process id in the parent, and *fd* is the file descriptor of the
1947 master end of the pseudo-terminal. For a more portable approach, use the
1948 :mod:`pty` module. If an error occurs :exc:`OSError` is raised.
[391]1949
[2]1950 Availability: some flavors of Unix.
1951
1952
1953.. function:: kill(pid, sig)
1954
1955 .. index::
1956 single: process; killing
1957 single: process; signalling
1958
1959 Send signal *sig* to the process *pid*. Constants for the specific signals
1960 available on the host platform are defined in the :mod:`signal` module.
1961
[391]1962 Windows: The :data:`signal.CTRL_C_EVENT` and
1963 :data:`signal.CTRL_BREAK_EVENT` signals are special signals which can
1964 only be sent to console processes which share a common console window,
1965 e.g., some subprocesses. Any other value for *sig* will cause the process
1966 to be unconditionally killed by the TerminateProcess API, and the exit code
1967 will be set to *sig*. The Windows version of :func:`kill` additionally takes
1968 process handles to be killed.
[2]1969
[391]1970 .. versionadded:: 2.7 Windows support
1971
1972
[2]1973.. function:: killpg(pgid, sig)
1974
1975 .. index::
1976 single: process; killing
1977 single: process; signalling
1978
[391]1979 Send the signal *sig* to the process group *pgid*.
[2]1980
[391]1981 Availability: Unix.
1982
[2]1983 .. versionadded:: 2.3
1984
1985
1986.. function:: nice(increment)
1987
1988 Add *increment* to the process's "niceness". Return the new niceness.
[391]1989
[2]1990 Availability: Unix.
1991
1992
1993.. function:: plock(op)
1994
1995 Lock program segments into memory. The value of *op* (defined in
[391]1996 ``<sys/lock.h>``) determines which segments are locked.
[2]1997
[391]1998 Availability: Unix.
[2]1999
[391]2000
[2]2001.. function:: popen(...)
2002 popen2(...)
2003 popen3(...)
2004 popen4(...)
2005 :noindex:
2006
2007 Run child processes, returning opened pipes for communications. These functions
2008 are described in section :ref:`os-newstreams`.
2009
2010
2011.. function:: spawnl(mode, path, ...)
2012 spawnle(mode, path, ..., env)
2013 spawnlp(mode, file, ...)
2014 spawnlpe(mode, file, ..., env)
2015 spawnv(mode, path, args)
2016 spawnve(mode, path, args, env)
2017 spawnvp(mode, file, args)
2018 spawnvpe(mode, file, args, env)
2019
2020 Execute the program *path* in a new process.
2021
2022 (Note that the :mod:`subprocess` module provides more powerful facilities for
2023 spawning new processes and retrieving their results; using that module is
2024 preferable to using these functions. Check especially the
2025 :ref:`subprocess-replacements` section.)
2026
2027 If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new
2028 process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
2029 exits normally, or ``-signal``, where *signal* is the signal that killed the
2030 process. On Windows, the process id will actually be the process handle, so can
2031 be used with the :func:`waitpid` function.
2032
[391]2033 The "l" and "v" variants of the :func:`spawn\* <spawnl>` functions differ in how
[2]2034 command-line arguments are passed. The "l" variants are perhaps the easiest
2035 to work with if the number of parameters is fixed when the code is written; the
2036 individual parameters simply become additional parameters to the
2037 :func:`spawnl\*` functions. The "v" variants are good when the number of
2038 parameters is variable, with the arguments being passed in a list or tuple as
2039 the *args* parameter. In either case, the arguments to the child process must
2040 start with the name of the command being run.
2041
2042 The variants which include a second "p" near the end (:func:`spawnlp`,
2043 :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
2044 :envvar:`PATH` environment variable to locate the program *file*. When the
[391]2045 environment is being replaced (using one of the :func:`spawn\*e <spawnl>` variants,
[2]2046 discussed in the next paragraph), the new environment is used as the source of
2047 the :envvar:`PATH` variable. The other variants, :func:`spawnl`,
2048 :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
2049 :envvar:`PATH` variable to locate the executable; *path* must contain an
2050 appropriate absolute or relative path.
2051
2052 For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
2053 (note that these all end in "e"), the *env* parameter must be a mapping
2054 which is used to define the environment variables for the new process (they are
2055 used instead of the current process' environment); the functions
2056 :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
2057 the new process to inherit the environment of the current process. Note that
2058 keys and values in the *env* dictionary must be strings; invalid keys or
2059 values will cause the function to fail, with a return value of ``127``.
2060
2061 As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are
2062 equivalent::
2063
2064 import os
2065 os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
2066
2067 L = ['cp', 'index.html', '/dev/null']
2068 os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
2069
2070 Availability: Unix, Windows. :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
[391]2071 and :func:`spawnvpe` are not available on Windows. :func:`spawnle` and
2072 :func:`spawnve` are not thread-safe on Windows; we advise you to use the
2073 :mod:`subprocess` module instead.
[2]2074
2075 .. versionadded:: 1.6
2076
2077
2078.. data:: P_NOWAIT
2079 P_NOWAITO
2080
[391]2081 Possible values for the *mode* parameter to the :func:`spawn\* <spawnl>` family of
[2]2082 functions. If either of these values is given, the :func:`spawn\*` functions
2083 will return as soon as the new process has been created, with the process id as
[391]2084 the return value.
[2]2085
[391]2086 Availability: Unix, Windows.
2087
[2]2088 .. versionadded:: 1.6
2089
2090
2091.. data:: P_WAIT
2092
[391]2093 Possible value for the *mode* parameter to the :func:`spawn\* <spawnl>` family of
[2]2094 functions. If this is given as *mode*, the :func:`spawn\*` functions will not
2095 return until the new process has run to completion and will return the exit code
2096 of the process the run is successful, or ``-signal`` if a signal kills the
[391]2097 process.
[2]2098
[391]2099 Availability: Unix, Windows.
2100
[2]2101 .. versionadded:: 1.6
2102
2103
2104.. data:: P_DETACH
2105 P_OVERLAY
2106
[391]2107 Possible values for the *mode* parameter to the :func:`spawn\* <spawnl>` family of
[2]2108 functions. These are less portable than those listed above. :const:`P_DETACH`
2109 is similar to :const:`P_NOWAIT`, but the new process is detached from the
2110 console of the calling process. If :const:`P_OVERLAY` is used, the current
2111 process will be replaced; the :func:`spawn\*` function will not return.
[391]2112
[2]2113 Availability: Windows.
2114
2115 .. versionadded:: 1.6
2116
2117
2118.. function:: startfile(path[, operation])
2119
2120 Start a file with its associated application.
2121
2122 When *operation* is not specified or ``'open'``, this acts like double-clicking
2123 the file in Windows Explorer, or giving the file name as an argument to the
2124 :program:`start` command from the interactive command shell: the file is opened
2125 with whatever application (if any) its extension is associated.
2126
2127 When another *operation* is given, it must be a "command verb" that specifies
2128 what should be done with the file. Common verbs documented by Microsoft are
2129 ``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` and
2130 ``'find'`` (to be used on directories).
2131
2132 :func:`startfile` returns as soon as the associated application is launched.
2133 There is no option to wait for the application to close, and no way to retrieve
2134 the application's exit status. The *path* parameter is relative to the current
2135 directory. If you want to use an absolute path, make sure the first character
[391]2136 is not a slash (``'/'``); the underlying Win32 :c:func:`ShellExecute` function
[2]2137 doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that
[391]2138 the path is properly encoded for Win32.
[2]2139
[391]2140 Availability: Windows.
2141
[2]2142 .. versionadded:: 2.0
2143
2144 .. versionadded:: 2.5
2145 The *operation* parameter.
2146
2147
2148.. function:: system(command)
2149
2150 Execute the command (a string) in a subshell. This is implemented by calling
[391]2151 the Standard C function :c:func:`system`, and has the same limitations.
[2]2152 Changes to :data:`sys.stdin`, etc. are not reflected in the environment of the
2153 executed command.
2154
2155 On Unix, the return value is the exit status of the process encoded in the
2156 format specified for :func:`wait`. Note that POSIX does not specify the meaning
[391]2157 of the return value of the C :c:func:`system` function, so the return value of
[2]2158 the Python function is system-dependent.
2159
2160 On Windows, the return value is that returned by the system shell after running
2161 *command*, given by the Windows environment variable :envvar:`COMSPEC`: on
2162 :program:`command.com` systems (Windows 95, 98 and ME) this is always ``0``; on
2163 :program:`cmd.exe` systems (Windows NT, 2000 and XP) this is the exit status of
2164 the command run; on systems using a non-native shell, consult your shell
2165 documentation.
2166
2167 The :mod:`subprocess` module provides more powerful facilities for spawning new
2168 processes and retrieving their results; using that module is preferable to using
[391]2169 this function. See the
2170 :ref:`subprocess-replacements` section in the :mod:`subprocess` documentation
2171 for some helpful recipes.
[2]2172
[391]2173 Availability: Unix, Windows.
[2]2174
[391]2175
[2]2176.. function:: times()
2177
[391]2178 Return a 5-tuple of floating point numbers indicating accumulated (processor
2179 or other) times, in seconds. The items are: user time, system time,
2180 children's user time, children's system time, and elapsed real time since a
2181 fixed point in the past, in that order. See the Unix manual page
2182 :manpage:`times(2)` or the corresponding Windows Platform API documentation.
2183 On Windows, only the first two items are filled, the others are zero.
[2]2184
[391]2185 Availability: Unix, Windows
[2]2186
[391]2187
[2]2188.. function:: wait()
2189
2190 Wait for completion of a child process, and return a tuple containing its pid
2191 and exit status indication: a 16-bit number, whose low byte is the signal number
2192 that killed the process, and whose high byte is the exit status (if the signal
2193 number is zero); the high bit of the low byte is set if a core file was
[391]2194 produced.
[2]2195
[391]2196 Availability: Unix.
[2]2197
[391]2198
[2]2199.. function:: waitpid(pid, options)
2200
2201 The details of this function differ on Unix and Windows.
2202
2203 On Unix: Wait for completion of a child process given by process id *pid*, and
2204 return a tuple containing its process id and exit status indication (encoded as
2205 for :func:`wait`). The semantics of the call are affected by the value of the
2206 integer *options*, which should be ``0`` for normal operation.
2207
2208 If *pid* is greater than ``0``, :func:`waitpid` requests status information for
2209 that specific process. If *pid* is ``0``, the request is for the status of any
2210 child in the process group of the current process. If *pid* is ``-1``, the
2211 request pertains to any child of the current process. If *pid* is less than
2212 ``-1``, status is requested for any process in the process group ``-pid`` (the
2213 absolute value of *pid*).
2214
2215 An :exc:`OSError` is raised with the value of errno when the syscall
2216 returns -1.
2217
2218 On Windows: Wait for completion of a process given by process handle *pid*, and
2219 return a tuple containing *pid*, and its exit status shifted left by 8 bits
2220 (shifting makes cross-platform use of the function easier). A *pid* less than or
2221 equal to ``0`` has no special meaning on Windows, and raises an exception. The
2222 value of integer *options* has no effect. *pid* can refer to any process whose
[391]2223 id is known, not necessarily a child process. The :func:`spawn\* <spawnl>`
2224 functions called with :const:`P_NOWAIT` return suitable process handles.
[2]2225
2226
[391]2227.. function:: wait3(options)
[2]2228
2229 Similar to :func:`waitpid`, except no process id argument is given and a
2230 3-element tuple containing the child's process id, exit status indication, and
2231 resource usage information is returned. Refer to :mod:`resource`.\
[391]2232 :func:`~resource.getrusage` for details on resource usage information. The
2233 option argument is the same as that provided to :func:`waitpid` and
2234 :func:`wait4`.
2235
[2]2236 Availability: Unix.
2237
2238 .. versionadded:: 2.5
2239
2240
2241.. function:: wait4(pid, options)
2242
2243 Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
2244 process id, exit status indication, and resource usage information is returned.
[391]2245 Refer to :mod:`resource`.\ :func:`~resource.getrusage` for details on
2246 resource usage information. The arguments to :func:`wait4` are the same as
2247 those provided to :func:`waitpid`.
[2]2248
[391]2249 Availability: Unix.
2250
[2]2251 .. versionadded:: 2.5
2252
2253
2254.. data:: WNOHANG
2255
2256 The option for :func:`waitpid` to return immediately if no child process status
2257 is available immediately. The function returns ``(0, 0)`` in this case.
[391]2258
[2]2259 Availability: Unix.
2260
2261
2262.. data:: WCONTINUED
2263
2264 This option causes child processes to be reported if they have been continued
[391]2265 from a job control stop since their status was last reported.
[2]2266
[391]2267 Availability: Some Unix systems.
2268
[2]2269 .. versionadded:: 2.3
2270
2271
2272.. data:: WUNTRACED
2273
2274 This option causes child processes to be reported if they have been stopped but
[391]2275 their current state has not been reported since they were stopped.
[2]2276
[391]2277 Availability: Unix.
2278
[2]2279 .. versionadded:: 2.3
2280
2281The following functions take a process status code as returned by
2282:func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be
2283used to determine the disposition of a process.
2284
2285
2286.. function:: WCOREDUMP(status)
2287
2288 Return ``True`` if a core dump was generated for the process, otherwise
[391]2289 return ``False``.
[2]2290
[391]2291 Availability: Unix.
2292
[2]2293 .. versionadded:: 2.3
2294
2295
2296.. function:: WIFCONTINUED(status)
2297
2298 Return ``True`` if the process has been continued from a job control stop,
[391]2299 otherwise return ``False``.
[2]2300
[391]2301 Availability: Unix.
2302
[2]2303 .. versionadded:: 2.3
2304
2305
2306.. function:: WIFSTOPPED(status)
2307
2308 Return ``True`` if the process has been stopped, otherwise return
[391]2309 ``False``.
[2]2310
[391]2311 Availability: Unix.
[2]2312
[391]2313
[2]2314.. function:: WIFSIGNALED(status)
2315
2316 Return ``True`` if the process exited due to a signal, otherwise return
[391]2317 ``False``.
[2]2318
[391]2319 Availability: Unix.
[2]2320
[391]2321
[2]2322.. function:: WIFEXITED(status)
2323
2324 Return ``True`` if the process exited using the :manpage:`exit(2)` system call,
[391]2325 otherwise return ``False``.
[2]2326
[391]2327 Availability: Unix.
[2]2328
[391]2329
[2]2330.. function:: WEXITSTATUS(status)
2331
2332 If ``WIFEXITED(status)`` is true, return the integer parameter to the
2333 :manpage:`exit(2)` system call. Otherwise, the return value is meaningless.
[391]2334
[2]2335 Availability: Unix.
2336
2337
2338.. function:: WSTOPSIG(status)
2339
[391]2340 Return the signal which caused the process to stop.
[2]2341
[391]2342 Availability: Unix.
[2]2343
[391]2344
[2]2345.. function:: WTERMSIG(status)
2346
[391]2347 Return the signal which caused the process to exit.
[2]2348
[391]2349 Availability: Unix.
[2]2350
[391]2351
[2]2352.. _os-path:
2353
2354Miscellaneous System Information
2355--------------------------------
2356
2357
2358.. function:: confstr(name)
2359
2360 Return string-valued system configuration values. *name* specifies the
2361 configuration value to retrieve; it may be a string which is the name of a
2362 defined system value; these names are specified in a number of standards (POSIX,
2363 Unix 95, Unix 98, and others). Some platforms define additional names as well.
2364 The names known to the host operating system are given as the keys of the
2365 ``confstr_names`` dictionary. For configuration variables not included in that
[391]2366 mapping, passing an integer for *name* is also accepted.
[2]2367
2368 If the configuration value specified by *name* isn't defined, ``None`` is
2369 returned.
2370
2371 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
2372 specific value for *name* is not supported by the host system, even if it is
2373 included in ``confstr_names``, an :exc:`OSError` is raised with
2374 :const:`errno.EINVAL` for the error number.
2375
[391]2376 Availability: Unix
[2]2377
[391]2378
[2]2379.. data:: confstr_names
2380
2381 Dictionary mapping names accepted by :func:`confstr` to the integer values
2382 defined for those names by the host operating system. This can be used to
[391]2383 determine the set of names known to the system.
[2]2384
[391]2385 Availability: Unix.
[2]2386
[391]2387
[2]2388.. function:: getloadavg()
2389
2390 Return the number of processes in the system run queue averaged over the last
2391 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was
[391]2392 unobtainable.
[2]2393
[391]2394 Availability: Unix.
2395
[2]2396 .. versionadded:: 2.3
2397
2398
2399.. function:: sysconf(name)
2400
2401 Return integer-valued system configuration values. If the configuration value
2402 specified by *name* isn't defined, ``-1`` is returned. The comments regarding
2403 the *name* parameter for :func:`confstr` apply here as well; the dictionary that
2404 provides information on the known names is given by ``sysconf_names``.
[391]2405
[2]2406 Availability: Unix.
2407
2408
2409.. data:: sysconf_names
2410
2411 Dictionary mapping names accepted by :func:`sysconf` to the integer values
2412 defined for those names by the host operating system. This can be used to
[391]2413 determine the set of names known to the system.
[2]2414
[391]2415 Availability: Unix.
2416
[2]2417The following data values are used to support path manipulation operations. These
2418are defined for all platforms.
2419
2420Higher-level operations on pathnames are defined in the :mod:`os.path` module.
2421
2422
2423.. data:: curdir
2424
2425 The constant string used by the operating system to refer to the current
2426 directory. This is ``'.'`` for Windows and POSIX. Also available via
2427 :mod:`os.path`.
2428
2429
2430.. data:: pardir
2431
2432 The constant string used by the operating system to refer to the parent
2433 directory. This is ``'..'`` for Windows and POSIX. Also available via
2434 :mod:`os.path`.
2435
2436
2437.. data:: sep
2438
2439 The character used by the operating system to separate pathname components.
2440 This is ``'/'`` for POSIX and ``'\\'`` for Windows. Note that knowing this
2441 is not sufficient to be able to parse or concatenate pathnames --- use
2442 :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
2443 useful. Also available via :mod:`os.path`.
2444
2445
2446.. data:: altsep
2447
2448 An alternative character used by the operating system to separate pathname
2449 components, or ``None`` if only one separator character exists. This is set to
2450 ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
2451 :mod:`os.path`.
2452
2453
2454.. data:: extsep
2455
2456 The character which separates the base filename from the extension; for example,
2457 the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.
2458
2459 .. versionadded:: 2.2
2460
2461
2462.. data:: pathsep
2463
2464 The character conventionally used by the operating system to separate search
2465 path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
2466 Windows. Also available via :mod:`os.path`.
2467
2468
2469.. data:: defpath
2470
[391]2471 The default search path used by :func:`exec\*p\* <execl>` and
2472 :func:`spawn\*p\* <spawnl>` if the environment doesn't have a ``'PATH'``
2473 key. Also available via :mod:`os.path`.
[2]2474
2475
2476.. data:: linesep
2477
2478 The string used to separate (or, rather, terminate) lines on the current
2479 platform. This may be a single character, such as ``'\n'`` for POSIX, or
2480 multiple characters, for example, ``'\r\n'`` for Windows. Do not use
2481 *os.linesep* as a line terminator when writing files opened in text mode (the
2482 default); use a single ``'\n'`` instead, on all platforms.
2483
2484
2485.. data:: devnull
2486
[391]2487 The file path of the null device. For example: ``'/dev/null'`` for
2488 POSIX, ``'nul'`` for Windows. Also available via :mod:`os.path`.
[2]2489
2490 .. versionadded:: 2.4
2491
2492
2493.. _os-miscfunc:
2494
2495Miscellaneous Functions
2496-----------------------
2497
2498
2499.. function:: urandom(n)
2500
2501 Return a string of *n* random bytes suitable for cryptographic use.
2502
2503 This function returns random bytes from an OS-specific randomness source. The
2504 returned data should be unpredictable enough for cryptographic applications,
2505 though its exact quality depends on the OS implementation. On a UNIX-like
[391]2506 system this will query ``/dev/urandom``, and on Windows it will use
2507 ``CryptGenRandom()``. If a randomness source is not found,
2508 :exc:`NotImplementedError` will be raised.
[2]2509
[391]2510 For an easy-to-use interface to the random number generator
2511 provided by your platform, please see :class:`random.SystemRandom`.
2512
[2]2513 .. versionadded:: 2.4
Note: See TracBrowser for help on using the repository browser.