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