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