blob: a776a6bb7d1148a21832b3aaf869ebc1469abb60 [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
Georg Brandl03b15c62007-11-01 17:19:33 +0000925 Like :func:`stat`, but do not follow symbolic links. This is an alias for
926 :func:`stat` on platforms that do not support symbolic links, such as
927 Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000928
929
930.. function:: mkfifo(path[, mode])
931
932 Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The default
933 *mode* is ``0666`` (octal). The current umask value is first masked out from
934 the mode. Availability: Macintosh, Unix.
935
936 FIFOs are pipes that can be accessed like regular files. FIFOs exist until they
937 are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
938 rendezvous between "client" and "server" type processes: the server opens the
939 FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo`
940 doesn't open the FIFO --- it just creates the rendezvous point.
941
942
943.. function:: mknod(filename[, mode=0600, device])
944
945 Create a filesystem node (file, device special file or named pipe) named
946 *filename*. *mode* specifies both the permissions to use and the type of node to
947 be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
948 ``stat.S_IFCHR``, ``stat.S_IFBLK``,
949 and ``stat.S_IFIFO`` (those constants are available in :mod:`stat`).
950 For ``stat.S_IFCHR`` and
951 ``stat.S_IFBLK``, *device* defines the newly created device special file (probably using
952 :func:`os.makedev`), otherwise it is ignored.
953
954 .. versionadded:: 2.3
955
956
957.. function:: major(device)
958
959 Extracts the device major number from a raw device number (usually the
960 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
961
962 .. versionadded:: 2.3
963
964
965.. function:: minor(device)
966
967 Extracts the device minor number from a raw device number (usually the
968 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
969
970 .. versionadded:: 2.3
971
972
973.. function:: makedev(major, minor)
974
975 Composes a raw device number from the major and minor device numbers.
976
977 .. versionadded:: 2.3
978
979
980.. function:: mkdir(path[, mode])
981
982 Create a directory named *path* with numeric mode *mode*. The default *mode* is
983 ``0777`` (octal). On some systems, *mode* is ignored. Where it is used, the
984 current umask value is first masked out. Availability: Macintosh, Unix, Windows.
985
986
987.. function:: makedirs(path[, mode])
988
989 .. index::
990 single: directory; creating
991 single: UNC paths; and os.makedirs()
992
993 Recursive directory creation function. Like :func:`mkdir`, but makes all
994 intermediate-level directories needed to contain the leaf directory. Throws an
995 :exc:`error` exception if the leaf directory already exists or cannot be
996 created. The default *mode* is ``0777`` (octal). On some systems, *mode* is
997 ignored. Where it is used, the current umask value is first masked out.
998
999 .. note::
1000
1001 :func:`makedirs` will become confused if the path elements to create include
1002 *os.pardir*.
1003
1004 .. versionadded:: 1.5.2
1005
1006 .. versionchanged:: 2.3
1007 This function now handles UNC paths correctly.
1008
1009
1010.. function:: pathconf(path, name)
1011
1012 Return system configuration information relevant to a named file. *name*
1013 specifies the configuration value to retrieve; it may be a string which is the
1014 name of a defined system value; these names are specified in a number of
1015 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
1016 additional names as well. The names known to the host operating system are
1017 given in the ``pathconf_names`` dictionary. For configuration variables not
1018 included in that mapping, passing an integer for *name* is also accepted.
1019 Availability: Macintosh, Unix.
1020
1021 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
1022 specific value for *name* is not supported by the host system, even if it is
1023 included in ``pathconf_names``, an :exc:`OSError` is raised with
1024 :const:`errno.EINVAL` for the error number.
1025
1026
1027.. data:: pathconf_names
1028
1029 Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
1030 the integer values defined for those names by the host operating system. This
1031 can be used to determine the set of names known to the system. Availability:
1032 Macintosh, Unix.
1033
1034
1035.. function:: readlink(path)
1036
1037 Return a string representing the path to which the symbolic link points. The
1038 result may be either an absolute or relative pathname; if it is relative, it may
1039 be converted to an absolute pathname using ``os.path.join(os.path.dirname(path),
1040 result)``.
1041
1042 .. versionchanged:: 2.6
1043 If the *path* is a Unicode object the result will also be a Unicode object.
1044
1045 Availability: Macintosh, Unix.
1046
1047
1048.. function:: remove(path)
1049
1050 Remove the file *path*. If *path* is a directory, :exc:`OSError` is raised; see
1051 :func:`rmdir` below to remove a directory. This is identical to the
1052 :func:`unlink` function documented below. On Windows, attempting to remove a
1053 file that is in use causes an exception to be raised; on Unix, the directory
1054 entry is removed but the storage allocated to the file is not made available
1055 until the original file is no longer in use. Availability: Macintosh, Unix,
1056 Windows.
1057
1058
1059.. function:: removedirs(path)
1060
1061 .. index:: single: directory; deleting
1062
1063 Removes directories recursively. Works like :func:`rmdir` except that, if the
1064 leaf directory is successfully removed, :func:`removedirs` tries to
1065 successively remove every parent directory mentioned in *path* until an error
1066 is raised (which is ignored, because it generally means that a parent directory
1067 is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
1068 the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
1069 they are empty. Raises :exc:`OSError` if the leaf directory could not be
1070 successfully removed.
1071
1072 .. versionadded:: 1.5.2
1073
1074
1075.. function:: rename(src, dst)
1076
1077 Rename the file or directory *src* to *dst*. If *dst* is a directory,
1078 :exc:`OSError` will be raised. On Unix, if *dst* exists and is a file, it will
1079 be removed silently if the user has permission. The operation may fail on some
1080 Unix flavors if *src* and *dst* are on different filesystems. If successful,
1081 the renaming will be an atomic operation (this is a POSIX requirement). On
1082 Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a
1083 file; there may be no way to implement an atomic rename when *dst* names an
1084 existing file. Availability: Macintosh, Unix, Windows.
1085
1086
1087.. function:: renames(old, new)
1088
1089 Recursive directory or file renaming function. Works like :func:`rename`, except
1090 creation of any intermediate directories needed to make the new pathname good is
1091 attempted first. After the rename, directories corresponding to rightmost path
1092 segments of the old name will be pruned away using :func:`removedirs`.
1093
1094 .. versionadded:: 1.5.2
1095
1096 .. note::
1097
1098 This function can fail with the new directory structure made if you lack
1099 permissions needed to remove the leaf directory or file.
1100
1101
1102.. function:: rmdir(path)
1103
1104 Remove the directory *path*. Availability: Macintosh, Unix, Windows.
1105
1106
1107.. function:: stat(path)
1108
1109 Perform a :cfunc:`stat` system call on the given path. The return value is an
1110 object whose attributes correspond to the members of the :ctype:`stat`
1111 structure, namely: :attr:`st_mode` (protection bits), :attr:`st_ino` (inode
1112 number), :attr:`st_dev` (device), :attr:`st_nlink` (number of hard links),
1113 :attr:`st_uid` (user ID of owner), :attr:`st_gid` (group ID of owner),
1114 :attr:`st_size` (size of file, in bytes), :attr:`st_atime` (time of most recent
1115 access), :attr:`st_mtime` (time of most recent content modification),
1116 :attr:`st_ctime` (platform dependent; time of most recent metadata change on
1117 Unix, or the time of creation on Windows)::
1118
1119 >>> import os
1120 >>> statinfo = os.stat('somefile.txt')
1121 >>> statinfo
1122 (33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
1123 >>> statinfo.st_size
1124 926L
1125 >>>
1126
1127 .. versionchanged:: 2.3
1128 If :func:`stat_float_times` returns true, the time values are floats, measuring
1129 seconds. Fractions of a second may be reported if the system supports that. On
1130 Mac OS, the times are always floats. See :func:`stat_float_times` for further
1131 discussion.
1132
1133 On some Unix systems (such as Linux), the following attributes may also be
1134 available: :attr:`st_blocks` (number of blocks allocated for file),
1135 :attr:`st_blksize` (filesystem blocksize), :attr:`st_rdev` (type of device if an
1136 inode device). :attr:`st_flags` (user defined flags for file).
1137
1138 On other Unix systems (such as FreeBSD), the following attributes may be
1139 available (but may be only filled out if root tries to use them): :attr:`st_gen`
1140 (file generation number), :attr:`st_birthtime` (time of file creation).
1141
1142 On Mac OS systems, the following attributes may also be available:
1143 :attr:`st_rsize`, :attr:`st_creator`, :attr:`st_type`.
1144
1145 On RISCOS systems, the following attributes are also available: :attr:`st_ftype`
1146 (file type), :attr:`st_attrs` (attributes), :attr:`st_obtype` (object type).
1147
1148 .. index:: module: stat
1149
1150 For backward compatibility, the return value of :func:`stat` is also accessible
1151 as a tuple of at least 10 integers giving the most important (and portable)
1152 members of the :ctype:`stat` structure, in the order :attr:`st_mode`,
1153 :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, :attr:`st_uid`,
1154 :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, :attr:`st_mtime`,
1155 :attr:`st_ctime`. More items may be added at the end by some implementations.
1156 The standard module :mod:`stat` defines functions and constants that are useful
1157 for extracting information from a :ctype:`stat` structure. (On Windows, some
1158 items are filled with dummy values.)
1159
1160 .. note::
1161
1162 The exact meaning and resolution of the :attr:`st_atime`, :attr:`st_mtime`, and
1163 :attr:`st_ctime` members depends on the operating system and the file system.
1164 For example, on Windows systems using the FAT or FAT32 file systems,
1165 :attr:`st_mtime` has 2-second resolution, and :attr:`st_atime` has only 1-day
1166 resolution. See your operating system documentation for details.
1167
1168 Availability: Macintosh, Unix, Windows.
1169
1170 .. versionchanged:: 2.2
1171 Added access to values as attributes of the returned object.
1172
1173 .. versionchanged:: 2.5
1174 Added st_gen, st_birthtime.
1175
1176
1177.. function:: stat_float_times([newvalue])
1178
1179 Determine whether :class:`stat_result` represents time stamps as float objects.
1180 If *newvalue* is ``True``, future calls to :func:`stat` return floats, if it is
1181 ``False``, future calls return ints. If *newvalue* is omitted, return the
1182 current setting.
1183
1184 For compatibility with older Python versions, accessing :class:`stat_result` as
1185 a tuple always returns integers.
1186
1187 .. versionchanged:: 2.5
1188 Python now returns float values by default. Applications which do not work
1189 correctly with floating point time stamps can use this function to restore the
1190 old behaviour.
1191
1192 The resolution of the timestamps (that is the smallest possible fraction)
1193 depends on the system. Some systems only support second resolution; on these
1194 systems, the fraction will always be zero.
1195
1196 It is recommended that this setting is only changed at program startup time in
1197 the *__main__* module; libraries should never change this setting. If an
1198 application uses a library that works incorrectly if floating point time stamps
1199 are processed, this application should turn the feature off until the library
1200 has been corrected.
1201
1202
1203.. function:: statvfs(path)
1204
1205 Perform a :cfunc:`statvfs` system call on the given path. The return value is
1206 an object whose attributes describe the filesystem on the given path, and
1207 correspond to the members of the :ctype:`statvfs` structure, namely:
1208 :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
1209 :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
1210 :attr:`f_flag`, :attr:`f_namemax`. Availability: Unix.
1211
1212 .. index:: module: statvfs
1213
1214 For backward compatibility, the return value is also accessible as a tuple whose
1215 values correspond to the attributes, in the order given above. The standard
1216 module :mod:`statvfs` defines constants that are useful for extracting
1217 information from a :ctype:`statvfs` structure when accessing it as a sequence;
1218 this remains useful when writing code that needs to work with versions of Python
1219 that don't support accessing the fields as attributes.
1220
1221 .. versionchanged:: 2.2
1222 Added access to values as attributes of the returned object.
1223
1224
1225.. function:: symlink(src, dst)
1226
1227 Create a symbolic link pointing to *src* named *dst*. Availability: Unix.
1228
1229
1230.. function:: tempnam([dir[, prefix]])
1231
1232 Return a unique path name that is reasonable for creating a temporary file.
1233 This will be an absolute path that names a potential directory entry in the
1234 directory *dir* or a common location for temporary files if *dir* is omitted or
1235 ``None``. If given and not ``None``, *prefix* is used to provide a short prefix
1236 to the filename. Applications are responsible for properly creating and
1237 managing files created using paths returned by :func:`tempnam`; no automatic
1238 cleanup is provided. On Unix, the environment variable :envvar:`TMPDIR`
1239 overrides *dir*, while on Windows the :envvar:`TMP` is used. The specific
1240 behavior of this function depends on the C library implementation; some aspects
1241 are underspecified in system documentation.
1242
1243 .. warning::
1244
1245 Use of :func:`tempnam` is vulnerable to symlink attacks; consider using
1246 :func:`tmpfile` (section :ref:`os-newstreams`) instead.
1247
1248 Availability: Macintosh, Unix, Windows.
1249
1250
1251.. function:: tmpnam()
1252
1253 Return a unique path name that is reasonable for creating a temporary file.
1254 This will be an absolute path that names a potential directory entry in a common
1255 location for temporary files. Applications are responsible for properly
1256 creating and managing files created using paths returned by :func:`tmpnam`; no
1257 automatic cleanup is provided.
1258
1259 .. warning::
1260
1261 Use of :func:`tmpnam` is vulnerable to symlink attacks; consider using
1262 :func:`tmpfile` (section :ref:`os-newstreams`) instead.
1263
1264 Availability: Unix, Windows. This function probably shouldn't be used on
1265 Windows, though: Microsoft's implementation of :func:`tmpnam` always creates a
1266 name in the root directory of the current drive, and that's generally a poor
1267 location for a temp file (depending on privileges, you may not even be able to
1268 open a file using this name).
1269
1270
1271.. data:: TMP_MAX
1272
1273 The maximum number of unique names that :func:`tmpnam` will generate before
1274 reusing names.
1275
1276
1277.. function:: unlink(path)
1278
1279 Remove the file *path*. This is the same function as :func:`remove`; the
1280 :func:`unlink` name is its traditional Unix name. Availability: Macintosh, Unix,
1281 Windows.
1282
1283
1284.. function:: utime(path, times)
1285
1286 Set the access and modified times of the file specified by *path*. If *times* is
1287 ``None``, then the file's access and modified times are set to the current time.
1288 Otherwise, *times* must be a 2-tuple of numbers, of the form ``(atime, mtime)``
1289 which is used to set the access and modified times, respectively. Whether a
1290 directory can be given for *path* depends on whether the operating system
1291 implements directories as files (for example, Windows does not). Note that the
1292 exact times you set here may not be returned by a subsequent :func:`stat` call,
1293 depending on the resolution with which your operating system records access and
1294 modification times; see :func:`stat`.
1295
1296 .. versionchanged:: 2.0
1297 Added support for ``None`` for *times*.
1298
1299 Availability: Macintosh, Unix, Windows.
1300
1301
1302.. function:: walk(top[, topdown=True [, onerror=None[, followlinks=False]]])
1303
1304 .. index::
1305 single: directory; walking
1306 single: directory; traversal
1307
1308 :func:`walk` generates the file names in a directory tree, by walking the tree
1309 either top down or bottom up. For each directory in the tree rooted at directory
1310 *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
1311 filenames)``.
1312
1313 *dirpath* is a string, the path to the directory. *dirnames* is a list of the
1314 names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``).
1315 *filenames* is a list of the names of the non-directory files in *dirpath*.
1316 Note that the names in the lists contain no path components. To get a full path
1317 (which begins with *top*) to a file or directory in *dirpath*, do
1318 ``os.path.join(dirpath, name)``.
1319
1320 If optional argument *topdown* is true or not specified, the triple for a
1321 directory is generated before the triples for any of its subdirectories
1322 (directories are generated top down). If *topdown* is false, the triple for a
1323 directory is generated after the triples for all of its subdirectories
1324 (directories are generated bottom up).
1325
1326 When *topdown* is true, the caller can modify the *dirnames* list in-place
1327 (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
1328 recurse into the subdirectories whose names remain in *dirnames*; this can be
1329 used to prune the search, impose a specific order of visiting, or even to inform
1330 :func:`walk` about directories the caller creates or renames before it resumes
1331 :func:`walk` again. Modifying *dirnames* when *topdown* is false is
1332 ineffective, because in bottom-up mode the directories in *dirnames* are
1333 generated before *dirpath* itself is generated.
1334
1335 By default errors from the ``os.listdir()`` call are ignored. If optional
1336 argument *onerror* is specified, it should be a function; it will be called with
1337 one argument, an :exc:`OSError` instance. It can report the error to continue
1338 with the walk, or raise the exception to abort the walk. Note that the filename
1339 is available as the ``filename`` attribute of the exception object.
1340
1341 By default, :func:`walk` will not walk down into symbolic links that resolve to
1342 directories. Set *followlinks* to True to visit directories pointed to by
1343 symlinks, on systems that support them.
1344
1345 .. versionadded:: 2.6
1346 The *followlinks* parameter.
1347
1348 .. note::
1349
1350 Be aware that setting *followlinks* to true can lead to infinite recursion if a
1351 link points to a parent directory of itself. :func:`walk` does not keep track of
1352 the directories it visited already.
1353
1354 .. note::
1355
1356 If you pass a relative pathname, don't change the current working directory
1357 between resumptions of :func:`walk`. :func:`walk` never changes the current
1358 directory, and assumes that its caller doesn't either.
1359
1360 This example displays the number of bytes taken by non-directory files in each
1361 directory under the starting directory, except that it doesn't look under any
1362 CVS subdirectory::
1363
1364 import os
1365 from os.path import join, getsize
1366 for root, dirs, files in os.walk('python/Lib/email'):
1367 print root, "consumes",
1368 print sum(getsize(join(root, name)) for name in files),
1369 print "bytes in", len(files), "non-directory files"
1370 if 'CVS' in dirs:
1371 dirs.remove('CVS') # don't visit CVS directories
1372
1373 In the next example, walking the tree bottom up is essential: :func:`rmdir`
1374 doesn't allow deleting a directory before the directory is empty::
1375
1376 # Delete everything reachable from the directory named in 'top',
1377 # assuming there are no symbolic links.
1378 # CAUTION: This is dangerous! For example, if top == '/', it
1379 # could delete all your disk files.
1380 import os
1381 for root, dirs, files in os.walk(top, topdown=False):
1382 for name in files:
1383 os.remove(os.path.join(root, name))
1384 for name in dirs:
1385 os.rmdir(os.path.join(root, name))
1386
1387 .. versionadded:: 2.3
1388
1389
1390.. _os-process:
1391
1392Process Management
1393------------------
1394
1395These functions may be used to create and manage processes.
1396
1397The various :func:`exec\*` functions take a list of arguments for the new
1398program loaded into the process. In each case, the first of these arguments is
1399passed to the new program as its own name rather than as an argument a user may
1400have typed on a command line. For the C programmer, this is the ``argv[0]``
1401passed to a program's :cfunc:`main`. For example, ``os.execv('/bin/echo',
1402['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
1403to be ignored.
1404
1405
1406.. function:: abort()
1407
1408 Generate a :const:`SIGABRT` signal to the current process. On Unix, the default
1409 behavior is to produce a core dump; on Windows, the process immediately returns
1410 an exit code of ``3``. Be aware that programs which use :func:`signal.signal`
1411 to register a handler for :const:`SIGABRT` will behave differently.
1412 Availability: Macintosh, Unix, Windows.
1413
1414
1415.. function:: execl(path, arg0, arg1, ...)
1416 execle(path, arg0, arg1, ..., env)
1417 execlp(file, arg0, arg1, ...)
1418 execlpe(file, arg0, arg1, ..., env)
1419 execv(path, args)
1420 execve(path, args, env)
1421 execvp(file, args)
1422 execvpe(file, args, env)
1423
1424 These functions all execute a new program, replacing the current process; they
1425 do not return. On Unix, the new executable is loaded into the current process,
1426 and will have the same process ID as the caller. Errors will be reported as
1427 :exc:`OSError` exceptions.
1428
1429 The ``'l'`` and ``'v'`` variants of the :func:`exec\*` functions differ in how
1430 command-line arguments are passed. The ``'l'`` variants are perhaps the easiest
1431 to work with if the number of parameters is fixed when the code is written; the
1432 individual parameters simply become additional parameters to the :func:`execl\*`
1433 functions. The ``'v'`` variants are good when the number of parameters is
1434 variable, with the arguments being passed in a list or tuple as the *args*
1435 parameter. In either case, the arguments to the child process should start with
1436 the name of the command being run, but this is not enforced.
1437
1438 The variants which include a ``'p'`` near the end (:func:`execlp`,
1439 :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
1440 :envvar:`PATH` environment variable to locate the program *file*. When the
1441 environment is being replaced (using one of the :func:`exec\*e` variants,
1442 discussed in the next paragraph), the new environment is used as the source of
1443 the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
1444 :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
1445 locate the executable; *path* must contain an appropriate absolute or relative
1446 path.
1447
1448 For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
1449 that these all end in ``'e'``), the *env* parameter must be a mapping which is
1450 used to define the environment variables for the new process; the :func:`execl`,
1451 :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
1452 inherit the environment of the current process. Availability: Macintosh, Unix,
1453 Windows.
1454
1455
1456.. function:: _exit(n)
1457
1458 Exit to the system with status *n*, without calling cleanup handlers, flushing
1459 stdio buffers, etc. Availability: Macintosh, Unix, Windows.
1460
1461 .. note::
1462
1463 The standard way to exit is ``sys.exit(n)``. :func:`_exit` should normally only
1464 be used in the child process after a :func:`fork`.
1465
1466The following exit codes are a defined, and can be used with :func:`_exit`,
1467although they are not required. These are typically used for system programs
1468written in Python, such as a mail server's external command delivery program.
1469
1470.. note::
1471
1472 Some of these may not be available on all Unix platforms, since there is some
1473 variation. These constants are defined where they are defined by the underlying
1474 platform.
1475
1476
1477.. data:: EX_OK
1478
1479 Exit code that means no error occurred. Availability: Macintosh, Unix.
1480
1481 .. versionadded:: 2.3
1482
1483
1484.. data:: EX_USAGE
1485
1486 Exit code that means the command was used incorrectly, such as when the wrong
1487 number of arguments are given. Availability: Macintosh, Unix.
1488
1489 .. versionadded:: 2.3
1490
1491
1492.. data:: EX_DATAERR
1493
1494 Exit code that means the input data was incorrect. Availability: Macintosh,
1495 Unix.
1496
1497 .. versionadded:: 2.3
1498
1499
1500.. data:: EX_NOINPUT
1501
1502 Exit code that means an input file did not exist or was not readable.
1503 Availability: Macintosh, Unix.
1504
1505 .. versionadded:: 2.3
1506
1507
1508.. data:: EX_NOUSER
1509
1510 Exit code that means a specified user did not exist. Availability: Macintosh,
1511 Unix.
1512
1513 .. versionadded:: 2.3
1514
1515
1516.. data:: EX_NOHOST
1517
1518 Exit code that means a specified host did not exist. Availability: Macintosh,
1519 Unix.
1520
1521 .. versionadded:: 2.3
1522
1523
1524.. data:: EX_UNAVAILABLE
1525
1526 Exit code that means that a required service is unavailable. Availability:
1527 Macintosh, Unix.
1528
1529 .. versionadded:: 2.3
1530
1531
1532.. data:: EX_SOFTWARE
1533
1534 Exit code that means an internal software error was detected. Availability:
1535 Macintosh, Unix.
1536
1537 .. versionadded:: 2.3
1538
1539
1540.. data:: EX_OSERR
1541
1542 Exit code that means an operating system error was detected, such as the
1543 inability to fork or create a pipe. Availability: Macintosh, Unix.
1544
1545 .. versionadded:: 2.3
1546
1547
1548.. data:: EX_OSFILE
1549
1550 Exit code that means some system file did not exist, could not be opened, or had
1551 some other kind of error. Availability: Macintosh, Unix.
1552
1553 .. versionadded:: 2.3
1554
1555
1556.. data:: EX_CANTCREAT
1557
1558 Exit code that means a user specified output file could not be created.
1559 Availability: Macintosh, Unix.
1560
1561 .. versionadded:: 2.3
1562
1563
1564.. data:: EX_IOERR
1565
1566 Exit code that means that an error occurred while doing I/O on some file.
1567 Availability: Macintosh, Unix.
1568
1569 .. versionadded:: 2.3
1570
1571
1572.. data:: EX_TEMPFAIL
1573
1574 Exit code that means a temporary failure occurred. This indicates something
1575 that may not really be an error, such as a network connection that couldn't be
1576 made during a retryable operation. Availability: Macintosh, Unix.
1577
1578 .. versionadded:: 2.3
1579
1580
1581.. data:: EX_PROTOCOL
1582
1583 Exit code that means that a protocol exchange was illegal, invalid, or not
1584 understood. Availability: Macintosh, Unix.
1585
1586 .. versionadded:: 2.3
1587
1588
1589.. data:: EX_NOPERM
1590
1591 Exit code that means that there were insufficient permissions to perform the
1592 operation (but not intended for file system problems). Availability: Macintosh,
1593 Unix.
1594
1595 .. versionadded:: 2.3
1596
1597
1598.. data:: EX_CONFIG
1599
1600 Exit code that means that some kind of configuration error occurred.
1601 Availability: Macintosh, Unix.
1602
1603 .. versionadded:: 2.3
1604
1605
1606.. data:: EX_NOTFOUND
1607
1608 Exit code that means something like "an entry was not found". Availability:
1609 Macintosh, Unix.
1610
1611 .. versionadded:: 2.3
1612
1613
1614.. function:: fork()
1615
1616 Fork a child process. Return ``0`` in the child, the child's process id in the
1617 parent. Availability: Macintosh, Unix.
1618
1619
1620.. function:: forkpty()
1621
1622 Fork a child process, using a new pseudo-terminal as the child's controlling
1623 terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
1624 new child's process id in the parent, and *fd* is the file descriptor of the
1625 master end of the pseudo-terminal. For a more portable approach, use the
1626 :mod:`pty` module. Availability: Macintosh, Some flavors of Unix.
1627
1628
1629.. function:: kill(pid, sig)
1630
1631 .. index::
1632 single: process; killing
1633 single: process; signalling
1634
1635 Send signal *sig* to the process *pid*. Constants for the specific signals
1636 available on the host platform are defined in the :mod:`signal` module.
1637 Availability: Macintosh, Unix.
1638
1639
1640.. function:: killpg(pgid, sig)
1641
1642 .. index::
1643 single: process; killing
1644 single: process; signalling
1645
1646 Send the signal *sig* to the process group *pgid*. Availability: Macintosh,
1647 Unix.
1648
1649 .. versionadded:: 2.3
1650
1651
1652.. function:: nice(increment)
1653
1654 Add *increment* to the process's "niceness". Return the new niceness.
1655 Availability: Macintosh, Unix.
1656
1657
1658.. function:: plock(op)
1659
1660 Lock program segments into memory. The value of *op* (defined in
1661 ``<sys/lock.h>``) determines which segments are locked. Availability: Macintosh,
1662 Unix.
1663
1664
1665.. function:: popen(...)
1666 popen2(...)
1667 popen3(...)
1668 popen4(...)
1669 :noindex:
1670
1671 Run child processes, returning opened pipes for communications. These functions
1672 are described in section :ref:`os-newstreams`.
1673
1674
1675.. function:: spawnl(mode, path, ...)
1676 spawnle(mode, path, ..., env)
1677 spawnlp(mode, file, ...)
1678 spawnlpe(mode, file, ..., env)
1679 spawnv(mode, path, args)
1680 spawnve(mode, path, args, env)
1681 spawnvp(mode, file, args)
1682 spawnvpe(mode, file, args, env)
1683
1684 Execute the program *path* in a new process.
1685
1686 (Note that the :mod:`subprocess` module provides more powerful facilities for
1687 spawning new processes and retrieving their results; using that module is
1688 preferable to using these functions.)
1689
1690 If *mode* is :const:`P_NOWAIT`, this function returns the process ID of the new
1691 process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
1692 exits normally, or ``-signal``, where *signal* is the signal that killed the
1693 process. On Windows, the process ID will actually be the process handle, so can
1694 be used with the :func:`waitpid` function.
1695
1696 The ``'l'`` and ``'v'`` variants of the :func:`spawn\*` functions differ in how
1697 command-line arguments are passed. The ``'l'`` variants are perhaps the easiest
1698 to work with if the number of parameters is fixed when the code is written; the
1699 individual parameters simply become additional parameters to the
1700 :func:`spawnl\*` functions. The ``'v'`` variants are good when the number of
1701 parameters is variable, with the arguments being passed in a list or tuple as
1702 the *args* parameter. In either case, the arguments to the child process must
1703 start with the name of the command being run.
1704
1705 The variants which include a second ``'p'`` near the end (:func:`spawnlp`,
1706 :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
1707 :envvar:`PATH` environment variable to locate the program *file*. When the
1708 environment is being replaced (using one of the :func:`spawn\*e` variants,
1709 discussed in the next paragraph), the new environment is used as the source of
1710 the :envvar:`PATH` variable. The other variants, :func:`spawnl`,
1711 :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
1712 :envvar:`PATH` variable to locate the executable; *path* must contain an
1713 appropriate absolute or relative path.
1714
1715 For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
1716 (note that these all end in ``'e'``), the *env* parameter must be a mapping
1717 which is used to define the environment variables for the new process; the
1718 :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
1719 the new process to inherit the environment of the current process.
1720
1721 As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are
1722 equivalent::
1723
1724 import os
1725 os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
1726
1727 L = ['cp', 'index.html', '/dev/null']
1728 os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
1729
1730 Availability: Unix, Windows. :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
1731 and :func:`spawnvpe` are not available on Windows.
1732
1733 .. versionadded:: 1.6
1734
1735
1736.. data:: P_NOWAIT
1737 P_NOWAITO
1738
1739 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1740 functions. If either of these values is given, the :func:`spawn\*` functions
1741 will return as soon as the new process has been created, with the process ID as
1742 the return value. Availability: Macintosh, Unix, Windows.
1743
1744 .. versionadded:: 1.6
1745
1746
1747.. data:: P_WAIT
1748
1749 Possible value for the *mode* parameter to the :func:`spawn\*` family of
1750 functions. If this is given as *mode*, the :func:`spawn\*` functions will not
1751 return until the new process has run to completion and will return the exit code
1752 of the process the run is successful, or ``-signal`` if a signal kills the
1753 process. Availability: Macintosh, Unix, Windows.
1754
1755 .. versionadded:: 1.6
1756
1757
1758.. data:: P_DETACH
1759 P_OVERLAY
1760
1761 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1762 functions. These are less portable than those listed above. :const:`P_DETACH`
1763 is similar to :const:`P_NOWAIT`, but the new process is detached from the
1764 console of the calling process. If :const:`P_OVERLAY` is used, the current
1765 process will be replaced; the :func:`spawn\*` function will not return.
1766 Availability: Windows.
1767
1768 .. versionadded:: 1.6
1769
1770
1771.. function:: startfile(path[, operation])
1772
1773 Start a file with its associated application.
1774
1775 When *operation* is not specified or ``'open'``, this acts like double-clicking
1776 the file in Windows Explorer, or giving the file name as an argument to the
1777 :program:`start` command from the interactive command shell: the file is opened
1778 with whatever application (if any) its extension is associated.
1779
1780 When another *operation* is given, it must be a "command verb" that specifies
1781 what should be done with the file. Common verbs documented by Microsoft are
1782 ``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` and
1783 ``'find'`` (to be used on directories).
1784
1785 :func:`startfile` returns as soon as the associated application is launched.
1786 There is no option to wait for the application to close, and no way to retrieve
1787 the application's exit status. The *path* parameter is relative to the current
1788 directory. If you want to use an absolute path, make sure the first character
1789 is not a slash (``'/'``); the underlying Win32 :cfunc:`ShellExecute` function
1790 doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that
1791 the path is properly encoded for Win32. Availability: Windows.
1792
1793 .. versionadded:: 2.0
1794
1795 .. versionadded:: 2.5
1796 The *operation* parameter.
1797
1798
1799.. function:: system(command)
1800
1801 Execute the command (a string) in a subshell. This is implemented by calling
1802 the Standard C function :cfunc:`system`, and has the same limitations. Changes
1803 to ``posix.environ``, ``sys.stdin``, etc. are not reflected in the environment
1804 of the executed command.
1805
1806 On Unix, the return value is the exit status of the process encoded in the
1807 format specified for :func:`wait`. Note that POSIX does not specify the meaning
1808 of the return value of the C :cfunc:`system` function, so the return value of
1809 the Python function is system-dependent.
1810
1811 On Windows, the return value is that returned by the system shell after running
1812 *command*, given by the Windows environment variable :envvar:`COMSPEC`: on
1813 :program:`command.com` systems (Windows 95, 98 and ME) this is always ``0``; on
1814 :program:`cmd.exe` systems (Windows NT, 2000 and XP) this is the exit status of
1815 the command run; on systems using a non-native shell, consult your shell
1816 documentation.
1817
1818 Availability: Macintosh, Unix, Windows.
1819
1820 The :mod:`subprocess` module provides more powerful facilities for spawning new
1821 processes and retrieving their results; using that module is preferable to using
1822 this function.
1823
1824
1825.. function:: times()
1826
1827 Return a 5-tuple of floating point numbers indicating accumulated (processor or
1828 other) times, in seconds. The items are: user time, system time, children's
1829 user time, children's system time, and elapsed real time since a fixed point in
1830 the past, in that order. See the Unix manual page :manpage:`times(2)` or the
1831 corresponding Windows Platform API documentation. Availability: Macintosh, Unix,
1832 Windows.
1833
1834
1835.. function:: wait()
1836
1837 Wait for completion of a child process, and return a tuple containing its pid
1838 and exit status indication: a 16-bit number, whose low byte is the signal number
1839 that killed the process, and whose high byte is the exit status (if the signal
1840 number is zero); the high bit of the low byte is set if a core file was
1841 produced. Availability: Macintosh, Unix.
1842
1843
1844.. function:: waitpid(pid, options)
1845
1846 The details of this function differ on Unix and Windows.
1847
1848 On Unix: Wait for completion of a child process given by process id *pid*, and
1849 return a tuple containing its process id and exit status indication (encoded as
1850 for :func:`wait`). The semantics of the call are affected by the value of the
1851 integer *options*, which should be ``0`` for normal operation.
1852
1853 If *pid* is greater than ``0``, :func:`waitpid` requests status information for
1854 that specific process. If *pid* is ``0``, the request is for the status of any
1855 child in the process group of the current process. If *pid* is ``-1``, the
1856 request pertains to any child of the current process. If *pid* is less than
1857 ``-1``, status is requested for any process in the process group ``-pid`` (the
1858 absolute value of *pid*).
1859
1860 On Windows: Wait for completion of a process given by process handle *pid*, and
1861 return a tuple containing *pid*, and its exit status shifted left by 8 bits
1862 (shifting makes cross-platform use of the function easier). A *pid* less than or
1863 equal to ``0`` has no special meaning on Windows, and raises an exception. The
1864 value of integer *options* has no effect. *pid* can refer to any process whose
1865 id is known, not necessarily a child process. The :func:`spawn` functions called
1866 with :const:`P_NOWAIT` return suitable process handles.
1867
1868
1869.. function:: wait3([options])
1870
1871 Similar to :func:`waitpid`, except no process id argument is given and a
1872 3-element tuple containing the child's process id, exit status indication, and
1873 resource usage information is returned. Refer to :mod:`resource`.\
1874 :func:`getrusage` for details on resource usage information. The option
1875 argument is the same as that provided to :func:`waitpid` and :func:`wait4`.
1876 Availability: Unix.
1877
1878 .. versionadded:: 2.5
1879
1880
1881.. function:: wait4(pid, options)
1882
1883 Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
1884 process id, exit status indication, and resource usage information is returned.
1885 Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage
1886 information. The arguments to :func:`wait4` are the same as those provided to
1887 :func:`waitpid`. Availability: Unix.
1888
1889 .. versionadded:: 2.5
1890
1891
1892.. data:: WNOHANG
1893
1894 The option for :func:`waitpid` to return immediately if no child process status
1895 is available immediately. The function returns ``(0, 0)`` in this case.
1896 Availability: Macintosh, Unix.
1897
1898
1899.. data:: WCONTINUED
1900
1901 This option causes child processes to be reported if they have been continued
1902 from a job control stop since their status was last reported. Availability: Some
1903 Unix systems.
1904
1905 .. versionadded:: 2.3
1906
1907
1908.. data:: WUNTRACED
1909
1910 This option causes child processes to be reported if they have been stopped but
1911 their current state has not been reported since they were stopped. Availability:
1912 Macintosh, Unix.
1913
1914 .. versionadded:: 2.3
1915
1916The following functions take a process status code as returned by
1917:func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be
1918used to determine the disposition of a process.
1919
1920
1921.. function:: WCOREDUMP(status)
1922
1923 Returns ``True`` if a core dump was generated for the process, otherwise it
1924 returns ``False``. Availability: Macintosh, Unix.
1925
1926 .. versionadded:: 2.3
1927
1928
1929.. function:: WIFCONTINUED(status)
1930
1931 Returns ``True`` if the process has been continued from a job control stop,
1932 otherwise it returns ``False``. Availability: Unix.
1933
1934 .. versionadded:: 2.3
1935
1936
1937.. function:: WIFSTOPPED(status)
1938
1939 Returns ``True`` if the process has been stopped, otherwise it returns
1940 ``False``. Availability: Unix.
1941
1942
1943.. function:: WIFSIGNALED(status)
1944
1945 Returns ``True`` if the process exited due to a signal, otherwise it returns
1946 ``False``. Availability: Macintosh, Unix.
1947
1948
1949.. function:: WIFEXITED(status)
1950
1951 Returns ``True`` if the process exited using the :manpage:`exit(2)` system call,
1952 otherwise it returns ``False``. Availability: Macintosh, Unix.
1953
1954
1955.. function:: WEXITSTATUS(status)
1956
1957 If ``WIFEXITED(status)`` is true, return the integer parameter to the
1958 :manpage:`exit(2)` system call. Otherwise, the return value is meaningless.
1959 Availability: Macintosh, Unix.
1960
1961
1962.. function:: WSTOPSIG(status)
1963
1964 Return the signal which caused the process to stop. Availability: Macintosh,
1965 Unix.
1966
1967
1968.. function:: WTERMSIG(status)
1969
1970 Return the signal which caused the process to exit. Availability: Macintosh,
1971 Unix.
1972
1973
1974.. _os-path:
1975
1976Miscellaneous System Information
1977--------------------------------
1978
1979
1980.. function:: confstr(name)
1981
1982 Return string-valued system configuration values. *name* specifies the
1983 configuration value to retrieve; it may be a string which is the name of a
1984 defined system value; these names are specified in a number of standards (POSIX,
1985 Unix 95, Unix 98, and others). Some platforms define additional names as well.
1986 The names known to the host operating system are given as the keys of the
1987 ``confstr_names`` dictionary. For configuration variables not included in that
1988 mapping, passing an integer for *name* is also accepted. Availability:
1989 Macintosh, Unix.
1990
1991 If the configuration value specified by *name* isn't defined, ``None`` is
1992 returned.
1993
1994 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
1995 specific value for *name* is not supported by the host system, even if it is
1996 included in ``confstr_names``, an :exc:`OSError` is raised with
1997 :const:`errno.EINVAL` for the error number.
1998
1999
2000.. data:: confstr_names
2001
2002 Dictionary mapping names accepted by :func:`confstr` to the integer values
2003 defined for those names by the host operating system. This can be used to
2004 determine the set of names known to the system. Availability: Macintosh, Unix.
2005
2006
2007.. function:: getloadavg()
2008
2009 Return the number of processes in the system run queue averaged over the last 1,
2010 5, and 15 minutes or raises :exc:`OSError` if the load average was
2011 unobtainable.
2012
2013 .. versionadded:: 2.3
2014
2015
2016.. function:: sysconf(name)
2017
2018 Return integer-valued system configuration values. If the configuration value
2019 specified by *name* isn't defined, ``-1`` is returned. The comments regarding
2020 the *name* parameter for :func:`confstr` apply here as well; the dictionary that
2021 provides information on the known names is given by ``sysconf_names``.
2022 Availability: Macintosh, Unix.
2023
2024
2025.. data:: sysconf_names
2026
2027 Dictionary mapping names accepted by :func:`sysconf` to the integer values
2028 defined for those names by the host operating system. This can be used to
2029 determine the set of names known to the system. Availability: Macintosh, Unix.
2030
2031The follow data values are used to support path manipulation operations. These
2032are defined for all platforms.
2033
2034Higher-level operations on pathnames are defined in the :mod:`os.path` module.
2035
2036
2037.. data:: curdir
2038
2039 The constant string used by the operating system to refer to the current
2040 directory. For example: ``'.'`` for POSIX or ``':'`` for Mac OS 9. Also
2041 available via :mod:`os.path`.
2042
2043
2044.. data:: pardir
2045
2046 The constant string used by the operating system to refer to the parent
2047 directory. For example: ``'..'`` for POSIX or ``'::'`` for Mac OS 9. Also
2048 available via :mod:`os.path`.
2049
2050
2051.. data:: sep
2052
2053 The character used by the operating system to separate pathname components, for
2054 example, ``'/'`` for POSIX or ``':'`` for Mac OS 9. Note that knowing this is
2055 not sufficient to be able to parse or concatenate pathnames --- use
2056 :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
2057 useful. Also available via :mod:`os.path`.
2058
2059
2060.. data:: altsep
2061
2062 An alternative character used by the operating system to separate pathname
2063 components, or ``None`` if only one separator character exists. This is set to
2064 ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
2065 :mod:`os.path`.
2066
2067
2068.. data:: extsep
2069
2070 The character which separates the base filename from the extension; for example,
2071 the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.
2072
2073 .. versionadded:: 2.2
2074
2075
2076.. data:: pathsep
2077
2078 The character conventionally used by the operating system to separate search
2079 path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
2080 Windows. Also available via :mod:`os.path`.
2081
2082
2083.. data:: defpath
2084
2085 The default search path used by :func:`exec\*p\*` and :func:`spawn\*p\*` if the
2086 environment doesn't have a ``'PATH'`` key. Also available via :mod:`os.path`.
2087
2088
2089.. data:: linesep
2090
2091 The string used to separate (or, rather, terminate) lines on the current
2092 platform. This may be a single character, such as ``'\n'`` for POSIX or
2093 ``'\r'`` for Mac OS, or multiple characters, for example, ``'\r\n'`` for
2094 Windows. Do not use *os.linesep* as a line terminator when writing files opened
2095 in text mode (the default); use a single ``'\n'`` instead, on all platforms.
2096
2097
2098.. data:: devnull
2099
2100 The file path of the null device. For example: ``'/dev/null'`` for POSIX or
2101 ``'Dev:Nul'`` for Mac OS 9. Also available via :mod:`os.path`.
2102
2103 .. versionadded:: 2.4
2104
2105
2106.. _os-miscfunc:
2107
2108Miscellaneous Functions
2109-----------------------
2110
2111
2112.. function:: urandom(n)
2113
2114 Return a string of *n* random bytes suitable for cryptographic use.
2115
2116 This function returns random bytes from an OS-specific randomness source. The
2117 returned data should be unpredictable enough for cryptographic applications,
2118 though its exact quality depends on the OS implementation. On a UNIX-like
2119 system this will query /dev/urandom, and on Windows it will use CryptGenRandom.
2120 If a randomness source is not found, :exc:`NotImplementedError` will be raised.
2121
2122 .. versionadded:: 2.4
2123