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