blob: 22b9a79e2dd3bc9b5933da59c088786a35923da3 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001:mod:`os` --- Miscellaneous operating system interfaces
2=======================================================
3
4.. module:: os
5 :synopsis: Miscellaneous operating system interfaces.
6
7
Georg Brandl57fe0f22008-01-12 10:53:29 +00008This module provides a portable way of using operating system dependent
9functionality. If you just want to read or write a file see :func:`open`, if
10you want to manipulate paths, see the :mod:`os.path` module, and if you want to
11read all the lines in all the files on the command line see the :mod:`fileinput`
12module. For creating temporary files and directories see the :mod:`tempfile`
13module, and for high-level file and directory handling see the :mod:`shutil`
14module.
Georg Brandl8ec7f652007-08-15 14:28:01 +000015
Georg Brandl57fe0f22008-01-12 10:53:29 +000016The design of all built-in operating system dependent modules of Python is such
17that as long as the same functionality is available, it uses the same interface;
18for example, the function ``os.stat(path)`` returns stat information about
19*path* in the same format (which happens to have originated with the POSIX
Georg Brandl8ec7f652007-08-15 14:28:01 +000020interface).
21
22Extensions peculiar to a particular operating system are also available through
23the :mod:`os` module, but using them is of course a threat to portability!
24
Georg Brandl57fe0f22008-01-12 10:53:29 +000025.. note::
Georg Brandl8ec7f652007-08-15 14:28:01 +000026
Georg Brandl57fe0f22008-01-12 10:53:29 +000027 All functions in this module raise :exc:`OSError` in the case of invalid or
28 inaccessible file names and paths, or other arguments that have the correct
29 type, but are not accepted by the operating system.
Georg Brandl8ec7f652007-08-15 14:28:01 +000030
Georg Brandl8ec7f652007-08-15 14:28:01 +000031
32.. exception:: error
33
Georg Brandl57fe0f22008-01-12 10:53:29 +000034 An alias for the built-in :exc:`OSError` exception.
Georg Brandl8ec7f652007-08-15 14:28:01 +000035
36
37.. data:: name
38
39 The name of the operating system dependent module imported. The following names
40 have currently been registered: ``'posix'``, ``'nt'``, ``'mac'``, ``'os2'``,
41 ``'ce'``, ``'java'``, ``'riscos'``.
42
43
44.. data:: path
45
46 The corresponding operating system dependent standard module for pathname
47 operations, such as :mod:`posixpath` or :mod:`macpath`. Thus, given the proper
48 imports, ``os.path.split(file)`` is equivalent to but more portable than
49 ``posixpath.split(file)``. Note that this is also an importable module: it may
50 be imported directly as :mod:`os.path`.
51
52
53.. _os-procinfo:
54
55Process Parameters
56------------------
57
58These functions and data items provide information and operate on the current
59process and user.
60
61
62.. data:: environ
63
64 A mapping object representing the string environment. For example,
65 ``environ['HOME']`` is the pathname of your home directory (on some platforms),
66 and is equivalent to ``getenv("HOME")`` in C.
67
68 This mapping is captured the first time the :mod:`os` module is imported,
69 typically during Python startup as part of processing :file:`site.py`. Changes
70 to the environment made after this time are not reflected in ``os.environ``,
71 except for changes made by modifying ``os.environ`` directly.
72
73 If the platform supports the :func:`putenv` function, this mapping may be used
74 to modify the environment as well as query the environment. :func:`putenv` will
75 be called automatically when the mapping is modified.
76
77 .. note::
78
79 Calling :func:`putenv` directly does not change ``os.environ``, so it's better
80 to modify ``os.environ``.
81
82 .. note::
83
84 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may cause
85 memory leaks. Refer to the system documentation for :cfunc:`putenv`.
86
87 If :func:`putenv` is not provided, a modified copy of this mapping may be
88 passed to the appropriate process-creation functions to cause child processes
89 to use a modified environment.
90
Georg Brandl4a212682007-09-20 17:57:59 +000091 If the platform supports the :func:`unsetenv` function, you can delete items in
Georg Brandl8ec7f652007-08-15 14:28:01 +000092 this mapping to unset environment variables. :func:`unsetenv` will be called
Georg Brandl4a212682007-09-20 17:57:59 +000093 automatically when an item is deleted from ``os.environ``, and when
Georg Brandl1a94ec22007-10-24 21:40:38 +000094 one of the :meth:`pop` or :meth:`clear` methods is called.
Georg Brandl4a212682007-09-20 17:57:59 +000095
96 .. versionchanged:: 2.6
Georg Brandl1a94ec22007-10-24 21:40:38 +000097 Also unset environment variables when calling :meth:`os.environ.clear`
98 and :meth:`os.environ.pop`.
Georg Brandl8ec7f652007-08-15 14:28:01 +000099
100
101.. function:: chdir(path)
102 fchdir(fd)
103 getcwd()
104 :noindex:
105
106 These functions are described in :ref:`os-file-dir`.
107
108
109.. function:: ctermid()
110
111 Return the filename corresponding to the controlling terminal of the process.
112 Availability: Unix.
113
114
115.. function:: getegid()
116
117 Return the effective group id of the current process. This corresponds to the
Georg Brandlf725b952008-01-05 19:44:22 +0000118 "set id" bit on the file being executed in the current process. Availability:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000119 Unix.
120
121
122.. function:: geteuid()
123
124 .. index:: single: user; effective id
125
Georg Brandlf725b952008-01-05 19:44:22 +0000126 Return the current process's effective user id. Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000127
128
129.. function:: getgid()
130
131 .. index:: single: process; group
132
133 Return the real group id of the current process. Availability: Unix.
134
135
136.. function:: getgroups()
137
138 Return list of supplemental group ids associated with the current process.
139 Availability: Unix.
140
141
142.. function:: getlogin()
143
144 Return the name of the user logged in on the controlling terminal of the
145 process. For most purposes, it is more useful to use the environment variable
146 :envvar:`LOGNAME` to find out who the user is, or
147 ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the currently
Georg Brandlf725b952008-01-05 19:44:22 +0000148 effective user id. Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000149
150
151.. function:: getpgid(pid)
152
153 Return the process group id of the process with process id *pid*. If *pid* is 0,
154 the process group id of the current process is returned. Availability: Unix.
155
156 .. versionadded:: 2.3
157
158
159.. function:: getpgrp()
160
161 .. index:: single: process; group
162
163 Return the id of the current process group. Availability: Unix.
164
165
166.. function:: getpid()
167
168 .. index:: single: process; id
169
170 Return the current process id. Availability: Unix, Windows.
171
172
173.. function:: getppid()
174
175 .. index:: single: process; id of parent
176
177 Return the parent's process id. Availability: Unix.
178
179
180.. function:: getuid()
181
182 .. index:: single: user; id
183
Georg Brandlf725b952008-01-05 19:44:22 +0000184 Return the current process's user id. Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000185
186
187.. function:: getenv(varname[, value])
188
189 Return the value of the environment variable *varname* if it exists, or *value*
190 if it doesn't. *value* defaults to ``None``. Availability: most flavors of
191 Unix, Windows.
192
193
194.. function:: putenv(varname, value)
195
196 .. index:: single: environment variables; setting
197
198 Set the environment variable named *varname* to the string *value*. Such
199 changes to the environment affect subprocesses started with :func:`os.system`,
200 :func:`popen` or :func:`fork` and :func:`execv`. Availability: most flavors of
201 Unix, Windows.
202
203 .. note::
204
205 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may cause
206 memory leaks. Refer to the system documentation for putenv.
207
208 When :func:`putenv` is supported, assignments to items in ``os.environ`` are
209 automatically translated into corresponding calls to :func:`putenv`; however,
210 calls to :func:`putenv` don't update ``os.environ``, so it is actually
211 preferable to assign to items of ``os.environ``.
212
213
214.. function:: setegid(egid)
215
216 Set the current process's effective group id. Availability: Unix.
217
218
219.. function:: seteuid(euid)
220
221 Set the current process's effective user id. Availability: Unix.
222
223
224.. function:: setgid(gid)
225
226 Set the current process' group id. Availability: Unix.
227
228
229.. function:: setgroups(groups)
230
231 Set the list of supplemental group ids associated with the current process to
232 *groups*. *groups* must be a sequence, and each element must be an integer
Georg Brandlf725b952008-01-05 19:44:22 +0000233 identifying a group. This operation is typically available only to the superuser.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000234 Availability: Unix.
235
236 .. versionadded:: 2.2
237
238
239.. function:: setpgrp()
240
Georg Brandlf725b952008-01-05 19:44:22 +0000241 Call the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on
Georg Brandl8ec7f652007-08-15 14:28:01 +0000242 which version is implemented (if any). See the Unix manual for the semantics.
243 Availability: Unix.
244
245
246.. function:: setpgid(pid, pgrp)
247
Georg Brandlf725b952008-01-05 19:44:22 +0000248 Call the system call :cfunc:`setpgid` to set the process group id of the
Georg Brandl8ec7f652007-08-15 14:28:01 +0000249 process with id *pid* to the process group with id *pgrp*. See the Unix manual
250 for the semantics. Availability: Unix.
251
252
253.. function:: setreuid(ruid, euid)
254
255 Set the current process's real and effective user ids. Availability: Unix.
256
257
258.. function:: setregid(rgid, egid)
259
260 Set the current process's real and effective group ids. Availability: Unix.
261
262
263.. function:: getsid(pid)
264
Georg Brandlf725b952008-01-05 19:44:22 +0000265 Call the system call :cfunc:`getsid`. See the Unix manual for the semantics.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000266 Availability: Unix.
267
268 .. versionadded:: 2.4
269
270
271.. function:: setsid()
272
Georg Brandlf725b952008-01-05 19:44:22 +0000273 Call the system call :cfunc:`setsid`. See the Unix manual for the semantics.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000274 Availability: Unix.
275
276
277.. function:: setuid(uid)
278
279 .. index:: single: user; id, setting
280
Georg Brandlf725b952008-01-05 19:44:22 +0000281 Set the current process's user id. Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000282
Georg Brandl8ec7f652007-08-15 14:28:01 +0000283
Georg Brandlb19be572007-12-29 10:57:00 +0000284.. placed in this section since it relates to errno.... a little weak
Georg Brandl8ec7f652007-08-15 14:28:01 +0000285.. function:: strerror(code)
286
287 Return the error message corresponding to the error code in *code*.
Georg Brandl3fc974f2008-05-11 21:16:37 +0000288 On platforms where :cfunc:`strerror` returns ``NULL`` when given an unknown
289 error number, :exc:`ValueError` is raised. Availability: Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000290
291
292.. function:: umask(mask)
293
Georg Brandlf725b952008-01-05 19:44:22 +0000294 Set the current numeric umask and return the previous umask. Availability:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000295 Unix, Windows.
296
297
298.. function:: uname()
299
300 .. index::
301 single: gethostname() (in module socket)
302 single: gethostbyaddr() (in module socket)
303
304 Return a 5-tuple containing information identifying the current operating
305 system. The tuple contains 5 strings: ``(sysname, nodename, release, version,
306 machine)``. Some systems truncate the nodename to 8 characters or to the
307 leading component; a better way to get the hostname is
308 :func:`socket.gethostname` or even
309 ``socket.gethostbyaddr(socket.gethostname())``. Availability: recent flavors of
310 Unix.
311
312
313.. function:: unsetenv(varname)
314
315 .. index:: single: environment variables; deleting
316
317 Unset (delete) the environment variable named *varname*. Such changes to the
318 environment affect subprocesses started with :func:`os.system`, :func:`popen` or
319 :func:`fork` and :func:`execv`. Availability: most flavors of Unix, Windows.
320
321 When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is
322 automatically translated into a corresponding call to :func:`unsetenv`; however,
323 calls to :func:`unsetenv` don't update ``os.environ``, so it is actually
324 preferable to delete items of ``os.environ``.
325
326
327.. _os-newstreams:
328
329File Object Creation
330--------------------
331
332These functions create new file objects. (See also :func:`open`.)
333
334
335.. function:: fdopen(fd[, mode[, bufsize]])
336
337 .. index:: single: I/O control; buffering
338
339 Return an open file object connected to the file descriptor *fd*. The *mode*
340 and *bufsize* arguments have the same meaning as the corresponding arguments to
341 the built-in :func:`open` function. Availability: Macintosh, Unix, Windows.
342
343 .. versionchanged:: 2.3
344 When specified, the *mode* argument must now start with one of the letters
345 ``'r'``, ``'w'``, or ``'a'``, otherwise a :exc:`ValueError` is raised.
346
347 .. versionchanged:: 2.5
348 On Unix, when the *mode* argument starts with ``'a'``, the *O_APPEND* flag is
349 set on the file descriptor (which the :cfunc:`fdopen` implementation already
350 does on most platforms).
351
352
353.. function:: popen(command[, mode[, bufsize]])
354
355 Open a pipe to or from *command*. The return value is an open file object
356 connected to the pipe, which can be read or written depending on whether *mode*
357 is ``'r'`` (default) or ``'w'``. The *bufsize* argument has the same meaning as
358 the corresponding argument to the built-in :func:`open` function. The exit
359 status of the command (encoded in the format specified for :func:`wait`) is
360 available as the return value of the :meth:`close` method of the file object,
361 except that when the exit status is zero (termination without errors), ``None``
362 is returned. Availability: Macintosh, Unix, Windows.
363
364 .. deprecated:: 2.6
Facundo Batista74a6ba82008-06-21 19:48:19 +0000365 This function is obsolete. Use the :mod:`subprocess` module. Check
Georg Brandl0ba92b22008-06-22 09:05:29 +0000366 especially the :ref:`subprocess-replacements` section.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000367
368 .. versionchanged:: 2.0
369 This function worked unreliably under Windows in earlier versions of Python.
370 This was due to the use of the :cfunc:`_popen` function from the libraries
371 provided with Windows. Newer versions of Python do not use the broken
372 implementation from the Windows libraries.
373
374
375.. function:: tmpfile()
376
377 Return a new file object opened in update mode (``w+b``). The file has no
378 directory entries associated with it and will be automatically deleted once
379 there are no file descriptors for the file. Availability: Macintosh, Unix,
380 Windows.
381
382There are a number of different :func:`popen\*` functions that provide slightly
383different ways to create subprocesses.
384
385.. deprecated:: 2.6
386 All of the :func:`popen\*` functions are obsolete. Use the :mod:`subprocess`
387 module.
388
389For each of the :func:`popen\*` variants, if *bufsize* is specified, it
390specifies the buffer size for the I/O pipes. *mode*, if provided, should be the
391string ``'b'`` or ``'t'``; on Windows this is needed to determine whether the
392file objects should be opened in binary or text mode. The default value for
393*mode* is ``'t'``.
394
395Also, for each of these variants, on Unix, *cmd* may be a sequence, in which
396case arguments will be passed directly to the program without shell intervention
397(as with :func:`os.spawnv`). If *cmd* is a string it will be passed to the shell
398(as with :func:`os.system`).
399
400These methods do not make it possible to retrieve the exit status from the child
401processes. The only way to control the input and output streams and also
402retrieve the return codes is to use the :mod:`subprocess` module; these are only
403available on Unix.
404
405For a discussion of possible deadlock conditions related to the use of these
406functions, see :ref:`popen2-flow-control`.
407
408
409.. function:: popen2(cmd[, mode[, bufsize]])
410
Georg Brandlf725b952008-01-05 19:44:22 +0000411 Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000412 child_stdout)``.
413
414 .. deprecated:: 2.6
Georg Brandl0ba92b22008-06-22 09:05:29 +0000415 This function is obsolete. Use the :mod:`subprocess` module. Check
416 especially the :ref:`subprocess-replacements` section.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000417
418 Availability: Macintosh, Unix, Windows.
419
420 .. versionadded:: 2.0
421
422
423.. function:: popen3(cmd[, mode[, bufsize]])
424
Georg Brandlf725b952008-01-05 19:44:22 +0000425 Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000426 child_stdout, child_stderr)``.
427
428 .. deprecated:: 2.6
Georg Brandl0ba92b22008-06-22 09:05:29 +0000429 This function is obsolete. Use the :mod:`subprocess` module. Check
430 especially the :ref:`subprocess-replacements` section.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000431
432 Availability: Macintosh, Unix, Windows.
433
434 .. versionadded:: 2.0
435
436
437.. function:: popen4(cmd[, mode[, bufsize]])
438
Georg Brandlf725b952008-01-05 19:44:22 +0000439 Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000440 child_stdout_and_stderr)``.
441
442 .. deprecated:: 2.6
Georg Brandl0ba92b22008-06-22 09:05:29 +0000443 This function is obsolete. Use the :mod:`subprocess` module. Check
444 especially the :ref:`subprocess-replacements` section.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000445
446 Availability: Macintosh, Unix, Windows.
447
448 .. versionadded:: 2.0
449
450(Note that ``child_stdin, child_stdout, and child_stderr`` are named from the
451point of view of the child process, so *child_stdin* is the child's standard
452input.)
453
454This functionality is also available in the :mod:`popen2` module using functions
455of the same names, but the return values of those functions have a different
456order.
457
458
459.. _os-fd-ops:
460
461File Descriptor Operations
462--------------------------
463
464These functions operate on I/O streams referenced using file descriptors.
465
466File descriptors are small integers corresponding to a file that has been opened
467by the current process. For example, standard input is usually file descriptor
4680, standard output is 1, and standard error is 2. Further files opened by a
469process will then be assigned 3, 4, 5, and so forth. The name "file descriptor"
470is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
471by file descriptors.
472
473
474.. function:: close(fd)
475
476 Close file descriptor *fd*. Availability: Macintosh, Unix, Windows.
477
478 .. note::
479
480 This function is intended for low-level I/O and must be applied to a file
481 descriptor as returned by :func:`open` or :func:`pipe`. To close a "file
482 object" returned by the built-in function :func:`open` or by :func:`popen` or
483 :func:`fdopen`, use its :meth:`close` method.
484
485
Georg Brandl309501a2008-01-19 20:22:13 +0000486.. function:: closerange(fd_low, fd_high)
487
488 Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive),
489 ignoring errors. Availability: Macintosh, Unix, Windows. Equivalent to::
490
491 for fd in xrange(fd_low, fd_high):
492 try:
493 os.close(fd)
494 except OSError:
495 pass
496
497 .. versionadded:: 2.6
498
499
Georg Brandl8ec7f652007-08-15 14:28:01 +0000500.. function:: dup(fd)
501
502 Return a duplicate of file descriptor *fd*. Availability: Macintosh, Unix,
503 Windows.
504
505
506.. function:: dup2(fd, fd2)
507
508 Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary.
509 Availability: Macintosh, Unix, Windows.
510
511
Christian Heimes36281872007-11-30 21:11:28 +0000512.. function:: fchmod(fd, mode)
513
514 Change the mode of the file given by *fd* to the numeric *mode*. See the docs
515 for :func:`chmod` for possible values of *mode*. Availability: Unix.
516
Georg Brandl81ddc1a2007-11-30 22:04:45 +0000517 .. versionadded:: 2.6
518
Christian Heimes36281872007-11-30 21:11:28 +0000519
520.. function:: fchown(fd, uid, gid)
521
522 Change the owner and group id of the file given by *fd* to the numeric *uid*
523 and *gid*. To leave one of the ids unchanged, set it to -1.
524 Availability: Unix.
525
Georg Brandl81ddc1a2007-11-30 22:04:45 +0000526 .. versionadded:: 2.6
527
Christian Heimes36281872007-11-30 21:11:28 +0000528
Georg Brandl8ec7f652007-08-15 14:28:01 +0000529.. function:: fdatasync(fd)
530
531 Force write of file with filedescriptor *fd* to disk. Does not force update of
532 metadata. Availability: Unix.
533
534
535.. function:: fpathconf(fd, name)
536
537 Return system configuration information relevant to an open file. *name*
538 specifies the configuration value to retrieve; it may be a string which is the
539 name of a defined system value; these names are specified in a number of
540 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
541 additional names as well. The names known to the host operating system are
542 given in the ``pathconf_names`` dictionary. For configuration variables not
543 included in that mapping, passing an integer for *name* is also accepted.
544 Availability: Macintosh, Unix.
545
546 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
547 specific value for *name* is not supported by the host system, even if it is
548 included in ``pathconf_names``, an :exc:`OSError` is raised with
549 :const:`errno.EINVAL` for the error number.
550
551
552.. function:: fstat(fd)
553
554 Return status for file descriptor *fd*, like :func:`stat`. Availability:
555 Macintosh, Unix, Windows.
556
557
558.. function:: fstatvfs(fd)
559
560 Return information about the filesystem containing the file associated with file
561 descriptor *fd*, like :func:`statvfs`. Availability: Unix.
562
563
564.. function:: fsync(fd)
565
566 Force write of file with filedescriptor *fd* to disk. On Unix, this calls the
567 native :cfunc:`fsync` function; on Windows, the MS :cfunc:`_commit` function.
568
569 If you're starting with a Python file object *f*, first do ``f.flush()``, and
570 then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated
571 with *f* are written to disk. Availability: Macintosh, Unix, and Windows
572 starting in 2.2.3.
573
574
575.. function:: ftruncate(fd, length)
576
577 Truncate the file corresponding to file descriptor *fd*, so that it is at most
578 *length* bytes in size. Availability: Macintosh, Unix.
579
580
581.. function:: isatty(fd)
582
583 Return ``True`` if the file descriptor *fd* is open and connected to a
584 tty(-like) device, else ``False``. Availability: Macintosh, Unix.
585
586
587.. function:: lseek(fd, pos, how)
588
Georg Brandlf725b952008-01-05 19:44:22 +0000589 Set the current position of file descriptor *fd* to position *pos*, modified
590 by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the
591 beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the
592 current position; :const:`os.SEEK_END` or ``2`` to set it relative to the end of
Georg Brandl8ec7f652007-08-15 14:28:01 +0000593 the file. Availability: Macintosh, Unix, Windows.
594
595
596.. function:: open(file, flags[, mode])
597
598 Open the file *file* and set various flags according to *flags* and possibly its
599 mode according to *mode*. The default *mode* is ``0777`` (octal), and the
600 current umask value is first masked out. Return the file descriptor for the
601 newly opened file. Availability: Macintosh, Unix, Windows.
602
603 For a description of the flag and mode values, see the C run-time documentation;
604 flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
605 this module too (see below).
606
607 .. note::
608
609 This function is intended for low-level I/O. For normal usage, use the built-in
610 function :func:`open`, which returns a "file object" with :meth:`read` and
611 :meth:`write` methods (and many more). To wrap a file descriptor in a "file
612 object", use :func:`fdopen`.
613
614
615.. function:: openpty()
616
617 .. index:: module: pty
618
619 Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master,
620 slave)`` for the pty and the tty, respectively. For a (slightly) more portable
Georg Brandlf725b952008-01-05 19:44:22 +0000621 approach, use the :mod:`pty` module. Availability: Macintosh, some flavors of
Georg Brandl8ec7f652007-08-15 14:28:01 +0000622 Unix.
623
624
625.. function:: pipe()
626
627 Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading
628 and writing, respectively. Availability: Macintosh, Unix, Windows.
629
630
631.. function:: read(fd, n)
632
633 Read at most *n* bytes from file descriptor *fd*. Return a string containing the
634 bytes read. If the end of the file referred to by *fd* has been reached, an
635 empty string is returned. Availability: Macintosh, Unix, Windows.
636
637 .. note::
638
639 This function is intended for low-level I/O and must be applied to a file
640 descriptor as returned by :func:`open` or :func:`pipe`. To read a "file object"
641 returned by the built-in function :func:`open` or by :func:`popen` or
Georg Brandlf725b952008-01-05 19:44:22 +0000642 :func:`fdopen`, or :data:`sys.stdin`, use its :meth:`read` or :meth:`readline`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000643 methods.
644
645
646.. function:: tcgetpgrp(fd)
647
648 Return the process group associated with the terminal given by *fd* (an open
649 file descriptor as returned by :func:`open`). Availability: Macintosh, Unix.
650
651
652.. function:: tcsetpgrp(fd, pg)
653
654 Set the process group associated with the terminal given by *fd* (an open file
655 descriptor as returned by :func:`open`) to *pg*. Availability: Macintosh, Unix.
656
657
658.. function:: ttyname(fd)
659
660 Return a string which specifies the terminal device associated with
Georg Brandlbb75e4e2007-10-21 10:46:24 +0000661 file descriptor *fd*. If *fd* is not associated with a terminal device, an
Georg Brandl8ec7f652007-08-15 14:28:01 +0000662 exception is raised. Availability:Macintosh, Unix.
663
664
665.. function:: write(fd, str)
666
667 Write the string *str* to file descriptor *fd*. Return the number of bytes
668 actually written. Availability: Macintosh, Unix, Windows.
669
670 .. note::
671
672 This function is intended for low-level I/O and must be applied to a file
673 descriptor as returned by :func:`open` or :func:`pipe`. To write a "file
674 object" returned by the built-in function :func:`open` or by :func:`popen` or
Georg Brandlf725b952008-01-05 19:44:22 +0000675 :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its :meth:`write`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000676 method.
677
678The following data items are available for use in constructing the *flags*
679parameter to the :func:`open` function. Some items will not be available on all
680platforms. For descriptions of their availability and use, consult
681:manpage:`open(2)`.
682
683
684.. data:: O_RDONLY
685 O_WRONLY
686 O_RDWR
687 O_APPEND
688 O_CREAT
689 O_EXCL
690 O_TRUNC
691
692 Options for the *flag* argument to the :func:`open` function. These can be
Georg Brandlf725b952008-01-05 19:44:22 +0000693 combined using the bitwise OR operator ``|``. Availability: Macintosh, Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000694
695
696.. data:: O_DSYNC
697 O_RSYNC
698 O_SYNC
699 O_NDELAY
700 O_NONBLOCK
701 O_NOCTTY
702 O_SHLOCK
703 O_EXLOCK
704
705 More options for the *flag* argument to the :func:`open` function. Availability:
706 Macintosh, Unix.
707
708
709.. data:: O_BINARY
Georg Brandlb67da6e2007-11-24 13:56:09 +0000710 O_NOINHERIT
Georg Brandl8ec7f652007-08-15 14:28:01 +0000711 O_SHORT_LIVED
712 O_TEMPORARY
713 O_RANDOM
714 O_SEQUENTIAL
715 O_TEXT
716
717 Options for the *flag* argument to the :func:`open` function. These can be
Georg Brandlf725b952008-01-05 19:44:22 +0000718 combined using the bitwise OR operator ``|``. Availability: Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000719
720
Georg Brandlae6b9f32008-05-16 13:41:26 +0000721.. data:: O_ASYNC
722 O_DIRECT
Georg Brandlb67da6e2007-11-24 13:56:09 +0000723 O_DIRECTORY
724 O_NOFOLLOW
725 O_NOATIME
726
727 Options for the *flag* argument to the :func:`open` function. These are
728 GNU extensions and not present if they are not defined by the C library.
729
730
Georg Brandl8ec7f652007-08-15 14:28:01 +0000731.. data:: SEEK_SET
732 SEEK_CUR
733 SEEK_END
734
735 Parameters to the :func:`lseek` function. Their values are 0, 1, and 2,
736 respectively. Availability: Windows, Macintosh, Unix.
737
738 .. versionadded:: 2.5
739
740
741.. _os-file-dir:
742
743Files and Directories
744---------------------
745
Georg Brandl8ec7f652007-08-15 14:28:01 +0000746.. function:: access(path, mode)
747
748 Use the real uid/gid to test for access to *path*. Note that most operations
749 will use the effective uid/gid, therefore this routine can be used in a
750 suid/sgid environment to test if the invoking user has the specified access to
751 *path*. *mode* should be :const:`F_OK` to test the existence of *path*, or it
752 can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and
753 :const:`X_OK` to test permissions. Return :const:`True` if access is allowed,
754 :const:`False` if not. See the Unix man page :manpage:`access(2)` for more
755 information. Availability: Macintosh, Unix, Windows.
756
757 .. note::
758
759 Using :func:`access` to check if a user is authorized to e.g. open a file before
760 actually doing so using :func:`open` creates a security hole, because the user
761 might exploit the short time interval between checking and opening the file to
762 manipulate it.
763
764 .. note::
765
766 I/O operations may fail even when :func:`access` indicates that they would
767 succeed, particularly for operations on network filesystems which may have
768 permissions semantics beyond the usual POSIX permission-bit model.
769
770
771.. data:: F_OK
772
773 Value to pass as the *mode* parameter of :func:`access` to test the existence of
774 *path*.
775
776
777.. data:: R_OK
778
779 Value to include in the *mode* parameter of :func:`access` to test the
780 readability of *path*.
781
782
783.. data:: W_OK
784
785 Value to include in the *mode* parameter of :func:`access` to test the
786 writability of *path*.
787
788
789.. data:: X_OK
790
791 Value to include in the *mode* parameter of :func:`access` to determine if
792 *path* can be executed.
793
794
795.. function:: chdir(path)
796
797 .. index:: single: directory; changing
798
799 Change the current working directory to *path*. Availability: Macintosh, Unix,
800 Windows.
801
802
803.. function:: fchdir(fd)
804
805 Change the current working directory to the directory represented by the file
806 descriptor *fd*. The descriptor must refer to an opened directory, not an open
807 file. Availability: Unix.
808
809 .. versionadded:: 2.3
810
811
812.. function:: getcwd()
813
814 Return a string representing the current working directory. Availability:
815 Macintosh, Unix, Windows.
816
817
818.. function:: getcwdu()
819
820 Return a Unicode object representing the current working directory.
821 Availability: Macintosh, Unix, Windows.
822
823 .. versionadded:: 2.3
824
825
826.. function:: chflags(path, flags)
827
828 Set the flags of *path* to the numeric *flags*. *flags* may take a combination
829 (bitwise OR) of the following values (as defined in the :mod:`stat` module):
830
831 * ``UF_NODUMP``
832 * ``UF_IMMUTABLE``
833 * ``UF_APPEND``
834 * ``UF_OPAQUE``
835 * ``UF_NOUNLINK``
836 * ``SF_ARCHIVED``
837 * ``SF_IMMUTABLE``
838 * ``SF_APPEND``
839 * ``SF_NOUNLINK``
840 * ``SF_SNAPSHOT``
841
842 Availability: Macintosh, Unix.
843
844 .. versionadded:: 2.6
845
846
847.. function:: chroot(path)
848
849 Change the root directory of the current process to *path*. Availability:
850 Macintosh, Unix.
851
852 .. versionadded:: 2.2
853
854
855.. function:: chmod(path, mode)
856
857 Change the mode of *path* to the numeric *mode*. *mode* may take one of the
Georg Brandlf725b952008-01-05 19:44:22 +0000858 following values (as defined in the :mod:`stat` module) or bitwise ORed
Georg Brandl8ec7f652007-08-15 14:28:01 +0000859 combinations of them:
860
861
862 * ``stat.S_ISUID``
863 * ``stat.S_ISGID``
864 * ``stat.S_ENFMT``
865 * ``stat.S_ISVTX``
866 * ``stat.S_IREAD``
867 * ``stat.S_IWRITE``
868 * ``stat.S_IEXEC``
869 * ``stat.S_IRWXU``
870 * ``stat.S_IRUSR``
871 * ``stat.S_IWUSR``
872 * ``stat.S_IXUSR``
873 * ``stat.S_IRWXG``
874 * ``stat.S_IRGRP``
875 * ``stat.S_IWGRP``
876 * ``stat.S_IXGRP``
877 * ``stat.S_IRWXO``
878 * ``stat.S_IROTH``
879 * ``stat.S_IWOTH``
880 * ``stat.S_IXOTH``
881
882 Availability: Macintosh, Unix, Windows.
883
884 .. note::
885
886 Although Windows supports :func:`chmod`, you can only set the file's read-only
887 flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD``
888 constants or a corresponding integer value). All other bits are
889 ignored.
890
891
892.. function:: chown(path, uid, gid)
893
894 Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave
895 one of the ids unchanged, set it to -1. Availability: Macintosh, Unix.
896
897
898.. function:: lchflags(path, flags)
899
900 Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not
901 follow symbolic links. Availability: Unix.
902
903 .. versionadded:: 2.6
904
905
Georg Brandl81ddc1a2007-11-30 22:04:45 +0000906.. function:: lchmod(path, mode)
907
908 Change the mode of *path* to the numeric *mode*. If path is a symlink, this
909 affects the symlink rather than the target. See the docs for :func:`chmod`
910 for possible values of *mode*. Availability: Unix.
911
912 .. versionadded:: 2.6
913
914
Georg Brandl8ec7f652007-08-15 14:28:01 +0000915.. function:: lchown(path, uid, gid)
916
Georg Brandlf725b952008-01-05 19:44:22 +0000917 Change the owner and group id of *path* to the numeric *uid* and *gid*. This
Georg Brandl8ec7f652007-08-15 14:28:01 +0000918 function will not follow symbolic links. Availability: Macintosh, Unix.
919
920 .. versionadded:: 2.3
921
922
923.. function:: link(src, dst)
924
925 Create a hard link pointing to *src* named *dst*. Availability: Macintosh, Unix.
926
927
928.. function:: listdir(path)
929
930 Return a list containing the names of the entries in the directory. The list is
931 in arbitrary order. It does not include the special entries ``'.'`` and
932 ``'..'`` even if they are present in the directory. Availability: Macintosh,
933 Unix, Windows.
934
935 .. versionchanged:: 2.3
936 On Windows NT/2k/XP and Unix, if *path* is a Unicode object, the result will be
937 a list of Unicode objects.
938
939
940.. function:: lstat(path)
941
Georg Brandl03b15c62007-11-01 17:19:33 +0000942 Like :func:`stat`, but do not follow symbolic links. This is an alias for
943 :func:`stat` on platforms that do not support symbolic links, such as
944 Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000945
946
947.. function:: mkfifo(path[, mode])
948
949 Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The default
950 *mode* is ``0666`` (octal). The current umask value is first masked out from
951 the mode. Availability: Macintosh, Unix.
952
953 FIFOs are pipes that can be accessed like regular files. FIFOs exist until they
954 are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
955 rendezvous between "client" and "server" type processes: the server opens the
956 FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo`
957 doesn't open the FIFO --- it just creates the rendezvous point.
958
959
960.. function:: mknod(filename[, mode=0600, device])
961
962 Create a filesystem node (file, device special file or named pipe) named
963 *filename*. *mode* specifies both the permissions to use and the type of node to
964 be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
965 ``stat.S_IFCHR``, ``stat.S_IFBLK``,
966 and ``stat.S_IFIFO`` (those constants are available in :mod:`stat`).
967 For ``stat.S_IFCHR`` and
968 ``stat.S_IFBLK``, *device* defines the newly created device special file (probably using
969 :func:`os.makedev`), otherwise it is ignored.
970
971 .. versionadded:: 2.3
972
973
974.. function:: major(device)
975
Georg Brandlf725b952008-01-05 19:44:22 +0000976 Extract the device major number from a raw device number (usually the
Georg Brandl8ec7f652007-08-15 14:28:01 +0000977 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
978
979 .. versionadded:: 2.3
980
981
982.. function:: minor(device)
983
Georg Brandlf725b952008-01-05 19:44:22 +0000984 Extract the device minor number from a raw device number (usually the
Georg Brandl8ec7f652007-08-15 14:28:01 +0000985 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
986
987 .. versionadded:: 2.3
988
989
990.. function:: makedev(major, minor)
991
Georg Brandlf725b952008-01-05 19:44:22 +0000992 Compose a raw device number from the major and minor device numbers.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000993
994 .. versionadded:: 2.3
995
996
997.. function:: mkdir(path[, mode])
998
999 Create a directory named *path* with numeric mode *mode*. The default *mode* is
1000 ``0777`` (octal). On some systems, *mode* is ignored. Where it is used, the
1001 current umask value is first masked out. Availability: Macintosh, Unix, Windows.
1002
Mark Summerfieldac3d4292007-11-02 08:24:59 +00001003 It is also possible to create temporary directories; see the
1004 :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
1005
Georg Brandl8ec7f652007-08-15 14:28:01 +00001006
1007.. function:: makedirs(path[, mode])
1008
1009 .. index::
1010 single: directory; creating
1011 single: UNC paths; and os.makedirs()
1012
1013 Recursive directory creation function. Like :func:`mkdir`, but makes all
1014 intermediate-level directories needed to contain the leaf directory. Throws an
1015 :exc:`error` exception if the leaf directory already exists or cannot be
1016 created. The default *mode* is ``0777`` (octal). On some systems, *mode* is
1017 ignored. Where it is used, the current umask value is first masked out.
1018
1019 .. note::
1020
1021 :func:`makedirs` will become confused if the path elements to create include
Georg Brandlf725b952008-01-05 19:44:22 +00001022 :data:`os.pardir`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001023
1024 .. versionadded:: 1.5.2
1025
1026 .. versionchanged:: 2.3
1027 This function now handles UNC paths correctly.
1028
1029
1030.. function:: pathconf(path, name)
1031
1032 Return system configuration information relevant to a named file. *name*
1033 specifies the configuration value to retrieve; it may be a string which is the
1034 name of a defined system value; these names are specified in a number of
1035 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
1036 additional names as well. The names known to the host operating system are
1037 given in the ``pathconf_names`` dictionary. For configuration variables not
1038 included in that mapping, passing an integer for *name* is also accepted.
1039 Availability: Macintosh, Unix.
1040
1041 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
1042 specific value for *name* is not supported by the host system, even if it is
1043 included in ``pathconf_names``, an :exc:`OSError` is raised with
1044 :const:`errno.EINVAL` for the error number.
1045
1046
1047.. data:: pathconf_names
1048
1049 Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
1050 the integer values defined for those names by the host operating system. This
1051 can be used to determine the set of names known to the system. Availability:
1052 Macintosh, Unix.
1053
1054
1055.. function:: readlink(path)
1056
1057 Return a string representing the path to which the symbolic link points. The
1058 result may be either an absolute or relative pathname; if it is relative, it may
1059 be converted to an absolute pathname using ``os.path.join(os.path.dirname(path),
1060 result)``.
1061
1062 .. versionchanged:: 2.6
1063 If the *path* is a Unicode object the result will also be a Unicode object.
1064
1065 Availability: Macintosh, Unix.
1066
1067
1068.. function:: remove(path)
1069
1070 Remove the file *path*. If *path* is a directory, :exc:`OSError` is raised; see
1071 :func:`rmdir` below to remove a directory. This is identical to the
1072 :func:`unlink` function documented below. On Windows, attempting to remove a
1073 file that is in use causes an exception to be raised; on Unix, the directory
1074 entry is removed but the storage allocated to the file is not made available
1075 until the original file is no longer in use. Availability: Macintosh, Unix,
1076 Windows.
1077
1078
1079.. function:: removedirs(path)
1080
1081 .. index:: single: directory; deleting
1082
Georg Brandlf725b952008-01-05 19:44:22 +00001083 Remove directories recursively. Works like :func:`rmdir` except that, if the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001084 leaf directory is successfully removed, :func:`removedirs` tries to
1085 successively remove every parent directory mentioned in *path* until an error
1086 is raised (which is ignored, because it generally means that a parent directory
1087 is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
1088 the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
1089 they are empty. Raises :exc:`OSError` if the leaf directory could not be
1090 successfully removed.
1091
1092 .. versionadded:: 1.5.2
1093
1094
1095.. function:: rename(src, dst)
1096
1097 Rename the file or directory *src* to *dst*. If *dst* is a directory,
1098 :exc:`OSError` will be raised. On Unix, if *dst* exists and is a file, it will
Georg Brandlf725b952008-01-05 19:44:22 +00001099 be replaced silently if the user has permission. The operation may fail on some
Georg Brandl8ec7f652007-08-15 14:28:01 +00001100 Unix flavors if *src* and *dst* are on different filesystems. If successful,
1101 the renaming will be an atomic operation (this is a POSIX requirement). On
1102 Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a
1103 file; there may be no way to implement an atomic rename when *dst* names an
1104 existing file. Availability: Macintosh, Unix, Windows.
1105
1106
1107.. function:: renames(old, new)
1108
1109 Recursive directory or file renaming function. Works like :func:`rename`, except
1110 creation of any intermediate directories needed to make the new pathname good is
1111 attempted first. After the rename, directories corresponding to rightmost path
1112 segments of the old name will be pruned away using :func:`removedirs`.
1113
1114 .. versionadded:: 1.5.2
1115
1116 .. note::
1117
1118 This function can fail with the new directory structure made if you lack
1119 permissions needed to remove the leaf directory or file.
1120
1121
1122.. function:: rmdir(path)
1123
1124 Remove the directory *path*. Availability: Macintosh, Unix, Windows.
1125
1126
1127.. function:: stat(path)
1128
1129 Perform a :cfunc:`stat` system call on the given path. The return value is an
1130 object whose attributes correspond to the members of the :ctype:`stat`
1131 structure, namely: :attr:`st_mode` (protection bits), :attr:`st_ino` (inode
1132 number), :attr:`st_dev` (device), :attr:`st_nlink` (number of hard links),
Georg Brandlf725b952008-01-05 19:44:22 +00001133 :attr:`st_uid` (user id of owner), :attr:`st_gid` (group id of owner),
Georg Brandl8ec7f652007-08-15 14:28:01 +00001134 :attr:`st_size` (size of file, in bytes), :attr:`st_atime` (time of most recent
1135 access), :attr:`st_mtime` (time of most recent content modification),
1136 :attr:`st_ctime` (platform dependent; time of most recent metadata change on
1137 Unix, or the time of creation on Windows)::
1138
1139 >>> import os
1140 >>> statinfo = os.stat('somefile.txt')
1141 >>> statinfo
1142 (33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
1143 >>> statinfo.st_size
1144 926L
1145 >>>
1146
1147 .. versionchanged:: 2.3
Georg Brandlf725b952008-01-05 19:44:22 +00001148 If :func:`stat_float_times` returns ``True``, the time values are floats, measuring
Georg Brandl8ec7f652007-08-15 14:28:01 +00001149 seconds. Fractions of a second may be reported if the system supports that. On
1150 Mac OS, the times are always floats. See :func:`stat_float_times` for further
1151 discussion.
1152
1153 On some Unix systems (such as Linux), the following attributes may also be
1154 available: :attr:`st_blocks` (number of blocks allocated for file),
1155 :attr:`st_blksize` (filesystem blocksize), :attr:`st_rdev` (type of device if an
1156 inode device). :attr:`st_flags` (user defined flags for file).
1157
1158 On other Unix systems (such as FreeBSD), the following attributes may be
1159 available (but may be only filled out if root tries to use them): :attr:`st_gen`
1160 (file generation number), :attr:`st_birthtime` (time of file creation).
1161
1162 On Mac OS systems, the following attributes may also be available:
1163 :attr:`st_rsize`, :attr:`st_creator`, :attr:`st_type`.
1164
1165 On RISCOS systems, the following attributes are also available: :attr:`st_ftype`
1166 (file type), :attr:`st_attrs` (attributes), :attr:`st_obtype` (object type).
1167
1168 .. index:: module: stat
1169
1170 For backward compatibility, the return value of :func:`stat` is also accessible
1171 as a tuple of at least 10 integers giving the most important (and portable)
1172 members of the :ctype:`stat` structure, in the order :attr:`st_mode`,
1173 :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, :attr:`st_uid`,
1174 :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, :attr:`st_mtime`,
1175 :attr:`st_ctime`. More items may be added at the end by some implementations.
1176 The standard module :mod:`stat` defines functions and constants that are useful
1177 for extracting information from a :ctype:`stat` structure. (On Windows, some
1178 items are filled with dummy values.)
1179
1180 .. note::
1181
1182 The exact meaning and resolution of the :attr:`st_atime`, :attr:`st_mtime`, and
1183 :attr:`st_ctime` members depends on the operating system and the file system.
1184 For example, on Windows systems using the FAT or FAT32 file systems,
1185 :attr:`st_mtime` has 2-second resolution, and :attr:`st_atime` has only 1-day
1186 resolution. See your operating system documentation for details.
1187
1188 Availability: Macintosh, Unix, Windows.
1189
1190 .. versionchanged:: 2.2
1191 Added access to values as attributes of the returned object.
1192
1193 .. versionchanged:: 2.5
Georg Brandlf725b952008-01-05 19:44:22 +00001194 Added :attr:`st_gen` and :attr:`st_birthtime`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001195
1196
1197.. function:: stat_float_times([newvalue])
1198
1199 Determine whether :class:`stat_result` represents time stamps as float objects.
1200 If *newvalue* is ``True``, future calls to :func:`stat` return floats, if it is
1201 ``False``, future calls return ints. If *newvalue* is omitted, return the
1202 current setting.
1203
1204 For compatibility with older Python versions, accessing :class:`stat_result` as
1205 a tuple always returns integers.
1206
1207 .. versionchanged:: 2.5
1208 Python now returns float values by default. Applications which do not work
1209 correctly with floating point time stamps can use this function to restore the
1210 old behaviour.
1211
1212 The resolution of the timestamps (that is the smallest possible fraction)
1213 depends on the system. Some systems only support second resolution; on these
1214 systems, the fraction will always be zero.
1215
1216 It is recommended that this setting is only changed at program startup time in
1217 the *__main__* module; libraries should never change this setting. If an
1218 application uses a library that works incorrectly if floating point time stamps
1219 are processed, this application should turn the feature off until the library
1220 has been corrected.
1221
1222
1223.. function:: statvfs(path)
1224
1225 Perform a :cfunc:`statvfs` system call on the given path. The return value is
1226 an object whose attributes describe the filesystem on the given path, and
1227 correspond to the members of the :ctype:`statvfs` structure, namely:
1228 :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
1229 :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
1230 :attr:`f_flag`, :attr:`f_namemax`. Availability: Unix.
1231
1232 .. index:: module: statvfs
1233
1234 For backward compatibility, the return value is also accessible as a tuple whose
1235 values correspond to the attributes, in the order given above. The standard
1236 module :mod:`statvfs` defines constants that are useful for extracting
1237 information from a :ctype:`statvfs` structure when accessing it as a sequence;
1238 this remains useful when writing code that needs to work with versions of Python
1239 that don't support accessing the fields as attributes.
1240
1241 .. versionchanged:: 2.2
1242 Added access to values as attributes of the returned object.
1243
1244
1245.. function:: symlink(src, dst)
1246
1247 Create a symbolic link pointing to *src* named *dst*. Availability: Unix.
1248
1249
1250.. function:: tempnam([dir[, prefix]])
1251
1252 Return a unique path name that is reasonable for creating a temporary file.
1253 This will be an absolute path that names a potential directory entry in the
1254 directory *dir* or a common location for temporary files if *dir* is omitted or
1255 ``None``. If given and not ``None``, *prefix* is used to provide a short prefix
1256 to the filename. Applications are responsible for properly creating and
1257 managing files created using paths returned by :func:`tempnam`; no automatic
1258 cleanup is provided. On Unix, the environment variable :envvar:`TMPDIR`
Georg Brandlf725b952008-01-05 19:44:22 +00001259 overrides *dir*, while on Windows :envvar:`TMP` is used. The specific
Georg Brandl8ec7f652007-08-15 14:28:01 +00001260 behavior of this function depends on the C library implementation; some aspects
1261 are underspecified in system documentation.
1262
1263 .. warning::
1264
1265 Use of :func:`tempnam` is vulnerable to symlink attacks; consider using
1266 :func:`tmpfile` (section :ref:`os-newstreams`) instead.
1267
1268 Availability: Macintosh, Unix, Windows.
1269
1270
1271.. function:: tmpnam()
1272
1273 Return a unique path name that is reasonable for creating a temporary file.
1274 This will be an absolute path that names a potential directory entry in a common
1275 location for temporary files. Applications are responsible for properly
1276 creating and managing files created using paths returned by :func:`tmpnam`; no
1277 automatic cleanup is provided.
1278
1279 .. warning::
1280
1281 Use of :func:`tmpnam` is vulnerable to symlink attacks; consider using
1282 :func:`tmpfile` (section :ref:`os-newstreams`) instead.
1283
1284 Availability: Unix, Windows. This function probably shouldn't be used on
1285 Windows, though: Microsoft's implementation of :func:`tmpnam` always creates a
1286 name in the root directory of the current drive, and that's generally a poor
1287 location for a temp file (depending on privileges, you may not even be able to
1288 open a file using this name).
1289
1290
1291.. data:: TMP_MAX
1292
1293 The maximum number of unique names that :func:`tmpnam` will generate before
1294 reusing names.
1295
1296
1297.. function:: unlink(path)
1298
1299 Remove the file *path*. This is the same function as :func:`remove`; the
1300 :func:`unlink` name is its traditional Unix name. Availability: Macintosh, Unix,
1301 Windows.
1302
1303
1304.. function:: utime(path, times)
1305
Benjamin Peterson5b02ef32008-08-16 03:13:07 +00001306 Set the access and modified times of the file specified by *path*. If *times*
1307 is ``None``, then the file's access and modified times are set to the current
1308 time. (The effect is similar to running the Unix program :program:`touch` on
1309 the path.) Otherwise, *times* must be a 2-tuple of numbers, of the form
1310 ``(atime, mtime)`` which is used to set the access and modified times,
1311 respectively. Whether a directory can be given for *path* depends on whether
1312 the operating system implements directories as files (for example, Windows
1313 does not). Note that the exact times you set here may not be returned by a
1314 subsequent :func:`stat` call, depending on the resolution with which your
1315 operating system records access and modification times; see :func:`stat`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001316
1317 .. versionchanged:: 2.0
1318 Added support for ``None`` for *times*.
1319
1320 Availability: Macintosh, Unix, Windows.
1321
1322
1323.. function:: walk(top[, topdown=True [, onerror=None[, followlinks=False]]])
1324
1325 .. index::
1326 single: directory; walking
1327 single: directory; traversal
1328
Georg Brandlf725b952008-01-05 19:44:22 +00001329 Generate the file names in a directory tree by walking the tree
1330 either top-down or bottom-up. For each directory in the tree rooted at directory
Georg Brandl8ec7f652007-08-15 14:28:01 +00001331 *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
1332 filenames)``.
1333
1334 *dirpath* is a string, the path to the directory. *dirnames* is a list of the
1335 names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``).
1336 *filenames* is a list of the names of the non-directory files in *dirpath*.
1337 Note that the names in the lists contain no path components. To get a full path
1338 (which begins with *top*) to a file or directory in *dirpath*, do
1339 ``os.path.join(dirpath, name)``.
1340
Georg Brandlf725b952008-01-05 19:44:22 +00001341 If optional argument *topdown* is ``True`` or not specified, the triple for a
Georg Brandl8ec7f652007-08-15 14:28:01 +00001342 directory is generated before the triples for any of its subdirectories
Georg Brandlf725b952008-01-05 19:44:22 +00001343 (directories are generated top-down). If *topdown* is ``False``, the triple for a
Georg Brandl8ec7f652007-08-15 14:28:01 +00001344 directory is generated after the triples for all of its subdirectories
Georg Brandlf725b952008-01-05 19:44:22 +00001345 (directories are generated bottom-up).
Georg Brandl8ec7f652007-08-15 14:28:01 +00001346
Georg Brandlf725b952008-01-05 19:44:22 +00001347 When *topdown* is ``True``, the caller can modify the *dirnames* list in-place
Georg Brandl8ec7f652007-08-15 14:28:01 +00001348 (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
1349 recurse into the subdirectories whose names remain in *dirnames*; this can be
1350 used to prune the search, impose a specific order of visiting, or even to inform
1351 :func:`walk` about directories the caller creates or renames before it resumes
Georg Brandlf725b952008-01-05 19:44:22 +00001352 :func:`walk` again. Modifying *dirnames* when *topdown* is ``False`` is
Georg Brandl8ec7f652007-08-15 14:28:01 +00001353 ineffective, because in bottom-up mode the directories in *dirnames* are
1354 generated before *dirpath* itself is generated.
1355
Georg Brandlf725b952008-01-05 19:44:22 +00001356 By default errors from the :func:`listdir` call are ignored. If optional
Georg Brandl8ec7f652007-08-15 14:28:01 +00001357 argument *onerror* is specified, it should be a function; it will be called with
1358 one argument, an :exc:`OSError` instance. It can report the error to continue
1359 with the walk, or raise the exception to abort the walk. Note that the filename
1360 is available as the ``filename`` attribute of the exception object.
1361
1362 By default, :func:`walk` will not walk down into symbolic links that resolve to
Georg Brandlf725b952008-01-05 19:44:22 +00001363 directories. Set *followlinks* to ``True`` to visit directories pointed to by
Georg Brandl8ec7f652007-08-15 14:28:01 +00001364 symlinks, on systems that support them.
1365
1366 .. versionadded:: 2.6
1367 The *followlinks* parameter.
1368
1369 .. note::
1370
Georg Brandlf725b952008-01-05 19:44:22 +00001371 Be aware that setting *followlinks* to ``True`` can lead to infinite recursion if a
Georg Brandl8ec7f652007-08-15 14:28:01 +00001372 link points to a parent directory of itself. :func:`walk` does not keep track of
1373 the directories it visited already.
1374
1375 .. note::
1376
1377 If you pass a relative pathname, don't change the current working directory
1378 between resumptions of :func:`walk`. :func:`walk` never changes the current
1379 directory, and assumes that its caller doesn't either.
1380
1381 This example displays the number of bytes taken by non-directory files in each
1382 directory under the starting directory, except that it doesn't look under any
1383 CVS subdirectory::
1384
1385 import os
1386 from os.path import join, getsize
1387 for root, dirs, files in os.walk('python/Lib/email'):
1388 print root, "consumes",
1389 print sum(getsize(join(root, name)) for name in files),
1390 print "bytes in", len(files), "non-directory files"
1391 if 'CVS' in dirs:
1392 dirs.remove('CVS') # don't visit CVS directories
1393
Georg Brandlf725b952008-01-05 19:44:22 +00001394 In the next example, walking the tree bottom-up is essential: :func:`rmdir`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001395 doesn't allow deleting a directory before the directory is empty::
1396
Georg Brandlf725b952008-01-05 19:44:22 +00001397 # Delete everything reachable from the directory named in "top",
Georg Brandl8ec7f652007-08-15 14:28:01 +00001398 # assuming there are no symbolic links.
1399 # CAUTION: This is dangerous! For example, if top == '/', it
1400 # could delete all your disk files.
1401 import os
1402 for root, dirs, files in os.walk(top, topdown=False):
1403 for name in files:
1404 os.remove(os.path.join(root, name))
1405 for name in dirs:
1406 os.rmdir(os.path.join(root, name))
1407
1408 .. versionadded:: 2.3
1409
1410
1411.. _os-process:
1412
1413Process Management
1414------------------
1415
1416These functions may be used to create and manage processes.
1417
1418The various :func:`exec\*` functions take a list of arguments for the new
1419program loaded into the process. In each case, the first of these arguments is
1420passed to the new program as its own name rather than as an argument a user may
1421have typed on a command line. For the C programmer, this is the ``argv[0]``
1422passed to a program's :cfunc:`main`. For example, ``os.execv('/bin/echo',
1423['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
1424to be ignored.
1425
1426
1427.. function:: abort()
1428
1429 Generate a :const:`SIGABRT` signal to the current process. On Unix, the default
1430 behavior is to produce a core dump; on Windows, the process immediately returns
1431 an exit code of ``3``. Be aware that programs which use :func:`signal.signal`
1432 to register a handler for :const:`SIGABRT` will behave differently.
1433 Availability: Macintosh, Unix, Windows.
1434
1435
1436.. function:: execl(path, arg0, arg1, ...)
1437 execle(path, arg0, arg1, ..., env)
1438 execlp(file, arg0, arg1, ...)
1439 execlpe(file, arg0, arg1, ..., env)
1440 execv(path, args)
1441 execve(path, args, env)
1442 execvp(file, args)
1443 execvpe(file, args, env)
1444
1445 These functions all execute a new program, replacing the current process; they
1446 do not return. On Unix, the new executable is loaded into the current process,
Georg Brandlf725b952008-01-05 19:44:22 +00001447 and will have the same process id as the caller. Errors will be reported as
Georg Brandl8ec7f652007-08-15 14:28:01 +00001448 :exc:`OSError` exceptions.
1449
Georg Brandlf725b952008-01-05 19:44:22 +00001450 The "l" and "v" variants of the :func:`exec\*` functions differ in how
1451 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl8ec7f652007-08-15 14:28:01 +00001452 to work with if the number of parameters is fixed when the code is written; the
1453 individual parameters simply become additional parameters to the :func:`execl\*`
Georg Brandlf725b952008-01-05 19:44:22 +00001454 functions. The "v" variants are good when the number of parameters is
Georg Brandl8ec7f652007-08-15 14:28:01 +00001455 variable, with the arguments being passed in a list or tuple as the *args*
1456 parameter. In either case, the arguments to the child process should start with
1457 the name of the command being run, but this is not enforced.
1458
Georg Brandlf725b952008-01-05 19:44:22 +00001459 The variants which include a "p" near the end (:func:`execlp`,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001460 :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
1461 :envvar:`PATH` environment variable to locate the program *file*. When the
1462 environment is being replaced (using one of the :func:`exec\*e` variants,
1463 discussed in the next paragraph), the new environment is used as the source of
1464 the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
1465 :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
1466 locate the executable; *path* must contain an appropriate absolute or relative
1467 path.
1468
1469 For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
Georg Brandlf725b952008-01-05 19:44:22 +00001470 that these all end in "e"), the *env* parameter must be a mapping which is
Georg Brandlfb246c42008-04-19 16:58:28 +00001471 used to define the environment variables for the new process (these are used
1472 instead of the current process' environment); the functions :func:`execl`,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001473 :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
1474 inherit the environment of the current process. Availability: Macintosh, Unix,
1475 Windows.
1476
1477
1478.. function:: _exit(n)
1479
1480 Exit to the system with status *n*, without calling cleanup handlers, flushing
1481 stdio buffers, etc. Availability: Macintosh, Unix, Windows.
1482
1483 .. note::
1484
1485 The standard way to exit is ``sys.exit(n)``. :func:`_exit` should normally only
1486 be used in the child process after a :func:`fork`.
1487
Georg Brandlf725b952008-01-05 19:44:22 +00001488The following exit codes are defined and can be used with :func:`_exit`,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001489although they are not required. These are typically used for system programs
1490written in Python, such as a mail server's external command delivery program.
1491
1492.. note::
1493
1494 Some of these may not be available on all Unix platforms, since there is some
1495 variation. These constants are defined where they are defined by the underlying
1496 platform.
1497
1498
1499.. data:: EX_OK
1500
1501 Exit code that means no error occurred. Availability: Macintosh, Unix.
1502
1503 .. versionadded:: 2.3
1504
1505
1506.. data:: EX_USAGE
1507
1508 Exit code that means the command was used incorrectly, such as when the wrong
1509 number of arguments are given. Availability: Macintosh, Unix.
1510
1511 .. versionadded:: 2.3
1512
1513
1514.. data:: EX_DATAERR
1515
1516 Exit code that means the input data was incorrect. Availability: Macintosh,
1517 Unix.
1518
1519 .. versionadded:: 2.3
1520
1521
1522.. data:: EX_NOINPUT
1523
1524 Exit code that means an input file did not exist or was not readable.
1525 Availability: Macintosh, Unix.
1526
1527 .. versionadded:: 2.3
1528
1529
1530.. data:: EX_NOUSER
1531
1532 Exit code that means a specified user did not exist. Availability: Macintosh,
1533 Unix.
1534
1535 .. versionadded:: 2.3
1536
1537
1538.. data:: EX_NOHOST
1539
1540 Exit code that means a specified host did not exist. Availability: Macintosh,
1541 Unix.
1542
1543 .. versionadded:: 2.3
1544
1545
1546.. data:: EX_UNAVAILABLE
1547
1548 Exit code that means that a required service is unavailable. Availability:
1549 Macintosh, Unix.
1550
1551 .. versionadded:: 2.3
1552
1553
1554.. data:: EX_SOFTWARE
1555
1556 Exit code that means an internal software error was detected. Availability:
1557 Macintosh, Unix.
1558
1559 .. versionadded:: 2.3
1560
1561
1562.. data:: EX_OSERR
1563
1564 Exit code that means an operating system error was detected, such as the
1565 inability to fork or create a pipe. Availability: Macintosh, Unix.
1566
1567 .. versionadded:: 2.3
1568
1569
1570.. data:: EX_OSFILE
1571
1572 Exit code that means some system file did not exist, could not be opened, or had
1573 some other kind of error. Availability: Macintosh, Unix.
1574
1575 .. versionadded:: 2.3
1576
1577
1578.. data:: EX_CANTCREAT
1579
1580 Exit code that means a user specified output file could not be created.
1581 Availability: Macintosh, Unix.
1582
1583 .. versionadded:: 2.3
1584
1585
1586.. data:: EX_IOERR
1587
1588 Exit code that means that an error occurred while doing I/O on some file.
1589 Availability: Macintosh, Unix.
1590
1591 .. versionadded:: 2.3
1592
1593
1594.. data:: EX_TEMPFAIL
1595
1596 Exit code that means a temporary failure occurred. This indicates something
1597 that may not really be an error, such as a network connection that couldn't be
1598 made during a retryable operation. Availability: Macintosh, Unix.
1599
1600 .. versionadded:: 2.3
1601
1602
1603.. data:: EX_PROTOCOL
1604
1605 Exit code that means that a protocol exchange was illegal, invalid, or not
1606 understood. Availability: Macintosh, Unix.
1607
1608 .. versionadded:: 2.3
1609
1610
1611.. data:: EX_NOPERM
1612
1613 Exit code that means that there were insufficient permissions to perform the
1614 operation (but not intended for file system problems). Availability: Macintosh,
1615 Unix.
1616
1617 .. versionadded:: 2.3
1618
1619
1620.. data:: EX_CONFIG
1621
1622 Exit code that means that some kind of configuration error occurred.
1623 Availability: Macintosh, Unix.
1624
1625 .. versionadded:: 2.3
1626
1627
1628.. data:: EX_NOTFOUND
1629
1630 Exit code that means something like "an entry was not found". Availability:
1631 Macintosh, Unix.
1632
1633 .. versionadded:: 2.3
1634
1635
1636.. function:: fork()
1637
Georg Brandlf725b952008-01-05 19:44:22 +00001638 Fork a child process. Return ``0`` in the child and the child's process id in the
Skip Montanaro75e51682008-03-15 02:32:49 +00001639 parent. If an error occurs :exc:`OSError` is raised.
1640 Availability: Macintosh, Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001641
1642
1643.. function:: forkpty()
1644
1645 Fork a child process, using a new pseudo-terminal as the child's controlling
1646 terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
1647 new child's process id in the parent, and *fd* is the file descriptor of the
1648 master end of the pseudo-terminal. For a more portable approach, use the
Skip Montanaro75e51682008-03-15 02:32:49 +00001649 :mod:`pty` module. If an error occurs :exc:`OSError` is raised.
1650 Availability: Macintosh, some flavors of Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001651
1652
1653.. function:: kill(pid, sig)
1654
1655 .. index::
1656 single: process; killing
1657 single: process; signalling
1658
1659 Send signal *sig* to the process *pid*. Constants for the specific signals
1660 available on the host platform are defined in the :mod:`signal` module.
1661 Availability: Macintosh, Unix.
1662
1663
1664.. function:: killpg(pgid, sig)
1665
1666 .. index::
1667 single: process; killing
1668 single: process; signalling
1669
1670 Send the signal *sig* to the process group *pgid*. Availability: Macintosh,
1671 Unix.
1672
1673 .. versionadded:: 2.3
1674
1675
1676.. function:: nice(increment)
1677
1678 Add *increment* to the process's "niceness". Return the new niceness.
1679 Availability: Macintosh, Unix.
1680
1681
1682.. function:: plock(op)
1683
1684 Lock program segments into memory. The value of *op* (defined in
1685 ``<sys/lock.h>``) determines which segments are locked. Availability: Macintosh,
1686 Unix.
1687
1688
1689.. function:: popen(...)
1690 popen2(...)
1691 popen3(...)
1692 popen4(...)
1693 :noindex:
1694
1695 Run child processes, returning opened pipes for communications. These functions
1696 are described in section :ref:`os-newstreams`.
1697
1698
1699.. function:: spawnl(mode, path, ...)
1700 spawnle(mode, path, ..., env)
1701 spawnlp(mode, file, ...)
1702 spawnlpe(mode, file, ..., env)
1703 spawnv(mode, path, args)
1704 spawnve(mode, path, args, env)
1705 spawnvp(mode, file, args)
1706 spawnvpe(mode, file, args, env)
1707
1708 Execute the program *path* in a new process.
1709
1710 (Note that the :mod:`subprocess` module provides more powerful facilities for
1711 spawning new processes and retrieving their results; using that module is
Facundo Batista74a6ba82008-06-21 19:48:19 +00001712 preferable to using these functions. Check specially the *Replacing Older
1713 Functions with the subprocess Module* section in that documentation page.)
Georg Brandl8ec7f652007-08-15 14:28:01 +00001714
Georg Brandlf725b952008-01-05 19:44:22 +00001715 If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new
Georg Brandl8ec7f652007-08-15 14:28:01 +00001716 process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
1717 exits normally, or ``-signal``, where *signal* is the signal that killed the
Georg Brandlf725b952008-01-05 19:44:22 +00001718 process. On Windows, the process id will actually be the process handle, so can
Georg Brandl8ec7f652007-08-15 14:28:01 +00001719 be used with the :func:`waitpid` function.
1720
Georg Brandlf725b952008-01-05 19:44:22 +00001721 The "l" and "v" variants of the :func:`spawn\*` functions differ in how
1722 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl8ec7f652007-08-15 14:28:01 +00001723 to work with if the number of parameters is fixed when the code is written; the
1724 individual parameters simply become additional parameters to the
Georg Brandlf725b952008-01-05 19:44:22 +00001725 :func:`spawnl\*` functions. The "v" variants are good when the number of
Georg Brandl8ec7f652007-08-15 14:28:01 +00001726 parameters is variable, with the arguments being passed in a list or tuple as
1727 the *args* parameter. In either case, the arguments to the child process must
1728 start with the name of the command being run.
1729
Georg Brandlf725b952008-01-05 19:44:22 +00001730 The variants which include a second "p" near the end (:func:`spawnlp`,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001731 :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
1732 :envvar:`PATH` environment variable to locate the program *file*. When the
1733 environment is being replaced (using one of the :func:`spawn\*e` variants,
1734 discussed in the next paragraph), the new environment is used as the source of
1735 the :envvar:`PATH` variable. The other variants, :func:`spawnl`,
1736 :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
1737 :envvar:`PATH` variable to locate the executable; *path* must contain an
1738 appropriate absolute or relative path.
1739
1740 For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
Georg Brandlf725b952008-01-05 19:44:22 +00001741 (note that these all end in "e"), the *env* parameter must be a mapping
Georg Brandlfb246c42008-04-19 16:58:28 +00001742 which is used to define the environment variables for the new process (they are
1743 used instead of the current process' environment); the functions
Georg Brandl8ec7f652007-08-15 14:28:01 +00001744 :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
Georg Brandl0ba92b22008-06-22 09:05:29 +00001848 this function. Use the :mod:`subprocess` module. Check especially the
1849 :ref:`subprocess-replacements` section.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001850
1851
1852.. function:: times()
1853
1854 Return a 5-tuple of floating point numbers indicating accumulated (processor or
1855 other) times, in seconds. The items are: user time, system time, children's
1856 user time, children's system time, and elapsed real time since a fixed point in
1857 the past, in that order. See the Unix manual page :manpage:`times(2)` or the
1858 corresponding Windows Platform API documentation. Availability: Macintosh, Unix,
Georg Brandl0a40ffb2008-02-13 07:20:22 +00001859 Windows. On Windows, only the first two items are filled, the others are zero.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001860
1861
1862.. function:: wait()
1863
1864 Wait for completion of a child process, and return a tuple containing its pid
1865 and exit status indication: a 16-bit number, whose low byte is the signal number
1866 that killed the process, and whose high byte is the exit status (if the signal
1867 number is zero); the high bit of the low byte is set if a core file was
1868 produced. Availability: Macintosh, Unix.
1869
1870
1871.. function:: waitpid(pid, options)
1872
1873 The details of this function differ on Unix and Windows.
1874
1875 On Unix: Wait for completion of a child process given by process id *pid*, and
1876 return a tuple containing its process id and exit status indication (encoded as
1877 for :func:`wait`). The semantics of the call are affected by the value of the
1878 integer *options*, which should be ``0`` for normal operation.
1879
1880 If *pid* is greater than ``0``, :func:`waitpid` requests status information for
1881 that specific process. If *pid* is ``0``, the request is for the status of any
1882 child in the process group of the current process. If *pid* is ``-1``, the
1883 request pertains to any child of the current process. If *pid* is less than
1884 ``-1``, status is requested for any process in the process group ``-pid`` (the
1885 absolute value of *pid*).
1886
Gregory P. Smith59de7f52008-08-15 23:14:00 +00001887 An :exc:`OSError` is raised with the value of errno when the syscall
1888 returns -1.
1889
Georg Brandl8ec7f652007-08-15 14:28:01 +00001890 On Windows: Wait for completion of a process given by process handle *pid*, and
1891 return a tuple containing *pid*, and its exit status shifted left by 8 bits
1892 (shifting makes cross-platform use of the function easier). A *pid* less than or
1893 equal to ``0`` has no special meaning on Windows, and raises an exception. The
1894 value of integer *options* has no effect. *pid* can refer to any process whose
1895 id is known, not necessarily a child process. The :func:`spawn` functions called
1896 with :const:`P_NOWAIT` return suitable process handles.
1897
1898
1899.. function:: wait3([options])
1900
1901 Similar to :func:`waitpid`, except no process id argument is given and a
1902 3-element tuple containing the child's process id, exit status indication, and
1903 resource usage information is returned. Refer to :mod:`resource`.\
1904 :func:`getrusage` for details on resource usage information. The option
1905 argument is the same as that provided to :func:`waitpid` and :func:`wait4`.
1906 Availability: Unix.
1907
1908 .. versionadded:: 2.5
1909
1910
1911.. function:: wait4(pid, options)
1912
1913 Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
1914 process id, exit status indication, and resource usage information is returned.
1915 Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage
1916 information. The arguments to :func:`wait4` are the same as those provided to
1917 :func:`waitpid`. Availability: Unix.
1918
1919 .. versionadded:: 2.5
1920
1921
1922.. data:: WNOHANG
1923
1924 The option for :func:`waitpid` to return immediately if no child process status
1925 is available immediately. The function returns ``(0, 0)`` in this case.
1926 Availability: Macintosh, Unix.
1927
1928
1929.. data:: WCONTINUED
1930
1931 This option causes child processes to be reported if they have been continued
1932 from a job control stop since their status was last reported. Availability: Some
1933 Unix systems.
1934
1935 .. versionadded:: 2.3
1936
1937
1938.. data:: WUNTRACED
1939
1940 This option causes child processes to be reported if they have been stopped but
1941 their current state has not been reported since they were stopped. Availability:
1942 Macintosh, Unix.
1943
1944 .. versionadded:: 2.3
1945
1946The following functions take a process status code as returned by
1947:func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be
1948used to determine the disposition of a process.
1949
1950
1951.. function:: WCOREDUMP(status)
1952
Georg Brandlf725b952008-01-05 19:44:22 +00001953 Return ``True`` if a core dump was generated for the process, otherwise
1954 return ``False``. Availability: Macintosh, Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001955
1956 .. versionadded:: 2.3
1957
1958
1959.. function:: WIFCONTINUED(status)
1960
Georg Brandlf725b952008-01-05 19:44:22 +00001961 Return ``True`` if the process has been continued from a job control stop,
1962 otherwise return ``False``. Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001963
1964 .. versionadded:: 2.3
1965
1966
1967.. function:: WIFSTOPPED(status)
1968
Georg Brandlf725b952008-01-05 19:44:22 +00001969 Return ``True`` if the process has been stopped, otherwise return
Georg Brandl8ec7f652007-08-15 14:28:01 +00001970 ``False``. Availability: Unix.
1971
1972
1973.. function:: WIFSIGNALED(status)
1974
Georg Brandlf725b952008-01-05 19:44:22 +00001975 Return ``True`` if the process exited due to a signal, otherwise return
Georg Brandl8ec7f652007-08-15 14:28:01 +00001976 ``False``. Availability: Macintosh, Unix.
1977
1978
1979.. function:: WIFEXITED(status)
1980
Georg Brandlf725b952008-01-05 19:44:22 +00001981 Return ``True`` if the process exited using the :manpage:`exit(2)` system call,
1982 otherwise return ``False``. Availability: Macintosh, Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001983
1984
1985.. function:: WEXITSTATUS(status)
1986
1987 If ``WIFEXITED(status)`` is true, return the integer parameter to the
1988 :manpage:`exit(2)` system call. Otherwise, the return value is meaningless.
1989 Availability: Macintosh, Unix.
1990
1991
1992.. function:: WSTOPSIG(status)
1993
1994 Return the signal which caused the process to stop. Availability: Macintosh,
1995 Unix.
1996
1997
1998.. function:: WTERMSIG(status)
1999
2000 Return the signal which caused the process to exit. Availability: Macintosh,
2001 Unix.
2002
2003
2004.. _os-path:
2005
2006Miscellaneous System Information
2007--------------------------------
2008
2009
2010.. function:: confstr(name)
2011
2012 Return string-valued system configuration values. *name* specifies the
2013 configuration value to retrieve; it may be a string which is the name of a
2014 defined system value; these names are specified in a number of standards (POSIX,
2015 Unix 95, Unix 98, and others). Some platforms define additional names as well.
2016 The names known to the host operating system are given as the keys of the
2017 ``confstr_names`` dictionary. For configuration variables not included in that
2018 mapping, passing an integer for *name* is also accepted. Availability:
2019 Macintosh, Unix.
2020
2021 If the configuration value specified by *name* isn't defined, ``None`` is
2022 returned.
2023
2024 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
2025 specific value for *name* is not supported by the host system, even if it is
2026 included in ``confstr_names``, an :exc:`OSError` is raised with
2027 :const:`errno.EINVAL` for the error number.
2028
2029
2030.. data:: confstr_names
2031
2032 Dictionary mapping names accepted by :func:`confstr` to the integer values
2033 defined for those names by the host operating system. This can be used to
2034 determine the set of names known to the system. Availability: Macintosh, Unix.
2035
2036
2037.. function:: getloadavg()
2038
Georg Brandl57fe0f22008-01-12 10:53:29 +00002039 Return the number of processes in the system run queue averaged over the last
2040 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was
Georg Brandl6bb7bcf2008-05-30 19:12:13 +00002041 unobtainable. Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00002042
2043 .. versionadded:: 2.3
2044
2045
2046.. function:: sysconf(name)
2047
2048 Return integer-valued system configuration values. If the configuration value
2049 specified by *name* isn't defined, ``-1`` is returned. The comments regarding
2050 the *name* parameter for :func:`confstr` apply here as well; the dictionary that
2051 provides information on the known names is given by ``sysconf_names``.
2052 Availability: Macintosh, Unix.
2053
2054
2055.. data:: sysconf_names
2056
2057 Dictionary mapping names accepted by :func:`sysconf` to the integer values
2058 defined for those names by the host operating system. This can be used to
2059 determine the set of names known to the system. Availability: Macintosh, Unix.
2060
Georg Brandlf725b952008-01-05 19:44:22 +00002061The following data values are used to support path manipulation operations. These
Georg Brandl8ec7f652007-08-15 14:28:01 +00002062are defined for all platforms.
2063
2064Higher-level operations on pathnames are defined in the :mod:`os.path` module.
2065
2066
2067.. data:: curdir
2068
2069 The constant string used by the operating system to refer to the current
2070 directory. For example: ``'.'`` for POSIX or ``':'`` for Mac OS 9. Also
2071 available via :mod:`os.path`.
2072
2073
2074.. data:: pardir
2075
2076 The constant string used by the operating system to refer to the parent
2077 directory. For example: ``'..'`` for POSIX or ``'::'`` for Mac OS 9. Also
2078 available via :mod:`os.path`.
2079
2080
2081.. data:: sep
2082
2083 The character used by the operating system to separate pathname components, for
2084 example, ``'/'`` for POSIX or ``':'`` for Mac OS 9. Note that knowing this is
2085 not sufficient to be able to parse or concatenate pathnames --- use
2086 :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
2087 useful. Also available via :mod:`os.path`.
2088
2089
2090.. data:: altsep
2091
2092 An alternative character used by the operating system to separate pathname
2093 components, or ``None`` if only one separator character exists. This is set to
2094 ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
2095 :mod:`os.path`.
2096
2097
2098.. data:: extsep
2099
2100 The character which separates the base filename from the extension; for example,
2101 the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.
2102
2103 .. versionadded:: 2.2
2104
2105
2106.. data:: pathsep
2107
2108 The character conventionally used by the operating system to separate search
2109 path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
2110 Windows. Also available via :mod:`os.path`.
2111
2112
2113.. data:: defpath
2114
2115 The default search path used by :func:`exec\*p\*` and :func:`spawn\*p\*` if the
2116 environment doesn't have a ``'PATH'`` key. Also available via :mod:`os.path`.
2117
2118
2119.. data:: linesep
2120
2121 The string used to separate (or, rather, terminate) lines on the current
2122 platform. This may be a single character, such as ``'\n'`` for POSIX or
2123 ``'\r'`` for Mac OS, or multiple characters, for example, ``'\r\n'`` for
2124 Windows. Do not use *os.linesep* as a line terminator when writing files opened
2125 in text mode (the default); use a single ``'\n'`` instead, on all platforms.
2126
2127
2128.. data:: devnull
2129
2130 The file path of the null device. For example: ``'/dev/null'`` for POSIX or
2131 ``'Dev:Nul'`` for Mac OS 9. Also available via :mod:`os.path`.
2132
2133 .. versionadded:: 2.4
2134
2135
2136.. _os-miscfunc:
2137
2138Miscellaneous Functions
2139-----------------------
2140
2141
2142.. function:: urandom(n)
2143
2144 Return a string of *n* random bytes suitable for cryptographic use.
2145
2146 This function returns random bytes from an OS-specific randomness source. The
2147 returned data should be unpredictable enough for cryptographic applications,
2148 though its exact quality depends on the OS implementation. On a UNIX-like
2149 system this will query /dev/urandom, and on Windows it will use CryptGenRandom.
2150 If a randomness source is not found, :exc:`NotImplementedError` will be raised.
2151
2152 .. versionadded:: 2.4
2153