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