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