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