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