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