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