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