blob: b39ec1bc6b97ca92ec93db5953c7f8989235d417 [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*.
288 Availability: Unix, Windows.
289
290
291.. function:: umask(mask)
292
Georg Brandlf725b952008-01-05 19:44:22 +0000293 Set the current numeric umask and return the previous umask. Availability:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000294 Unix, Windows.
295
296
297.. function:: uname()
298
299 .. index::
300 single: gethostname() (in module socket)
301 single: gethostbyaddr() (in module socket)
302
303 Return a 5-tuple containing information identifying the current operating
304 system. The tuple contains 5 strings: ``(sysname, nodename, release, version,
305 machine)``. Some systems truncate the nodename to 8 characters or to the
306 leading component; a better way to get the hostname is
307 :func:`socket.gethostname` or even
308 ``socket.gethostbyaddr(socket.gethostname())``. Availability: recent flavors of
309 Unix.
310
311
312.. function:: unsetenv(varname)
313
314 .. index:: single: environment variables; deleting
315
316 Unset (delete) the environment variable named *varname*. Such changes to the
317 environment affect subprocesses started with :func:`os.system`, :func:`popen` or
318 :func:`fork` and :func:`execv`. Availability: most flavors of Unix, Windows.
319
320 When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is
321 automatically translated into a corresponding call to :func:`unsetenv`; however,
322 calls to :func:`unsetenv` don't update ``os.environ``, so it is actually
323 preferable to delete items of ``os.environ``.
324
325
326.. _os-newstreams:
327
328File Object Creation
329--------------------
330
331These functions create new file objects. (See also :func:`open`.)
332
333
334.. function:: fdopen(fd[, mode[, bufsize]])
335
336 .. index:: single: I/O control; buffering
337
338 Return an open file object connected to the file descriptor *fd*. The *mode*
339 and *bufsize* arguments have the same meaning as the corresponding arguments to
340 the built-in :func:`open` function. Availability: Macintosh, Unix, Windows.
341
342 .. versionchanged:: 2.3
343 When specified, the *mode* argument must now start with one of the letters
344 ``'r'``, ``'w'``, or ``'a'``, otherwise a :exc:`ValueError` is raised.
345
346 .. versionchanged:: 2.5
347 On Unix, when the *mode* argument starts with ``'a'``, the *O_APPEND* flag is
348 set on the file descriptor (which the :cfunc:`fdopen` implementation already
349 does on most platforms).
350
351
352.. function:: popen(command[, mode[, bufsize]])
353
354 Open a pipe to or from *command*. The return value is an open file object
355 connected to the pipe, which can be read or written depending on whether *mode*
356 is ``'r'`` (default) or ``'w'``. The *bufsize* argument has the same meaning as
357 the corresponding argument to the built-in :func:`open` function. The exit
358 status of the command (encoded in the format specified for :func:`wait`) is
359 available as the return value of the :meth:`close` method of the file object,
360 except that when the exit status is zero (termination without errors), ``None``
361 is returned. Availability: Macintosh, Unix, Windows.
362
363 .. deprecated:: 2.6
364 This function is obsolete. Use the :mod:`subprocess` module.
365
366 .. versionchanged:: 2.0
367 This function worked unreliably under Windows in earlier versions of Python.
368 This was due to the use of the :cfunc:`_popen` function from the libraries
369 provided with Windows. Newer versions of Python do not use the broken
370 implementation from the Windows libraries.
371
372
373.. function:: tmpfile()
374
375 Return a new file object opened in update mode (``w+b``). The file has no
376 directory entries associated with it and will be automatically deleted once
377 there are no file descriptors for the file. Availability: Macintosh, Unix,
378 Windows.
379
380There are a number of different :func:`popen\*` functions that provide slightly
381different ways to create subprocesses.
382
383.. deprecated:: 2.6
384 All of the :func:`popen\*` functions are obsolete. Use the :mod:`subprocess`
385 module.
386
387For each of the :func:`popen\*` variants, if *bufsize* is specified, it
388specifies the buffer size for the I/O pipes. *mode*, if provided, should be the
389string ``'b'`` or ``'t'``; on Windows this is needed to determine whether the
390file objects should be opened in binary or text mode. The default value for
391*mode* is ``'t'``.
392
393Also, for each of these variants, on Unix, *cmd* may be a sequence, in which
394case arguments will be passed directly to the program without shell intervention
395(as with :func:`os.spawnv`). If *cmd* is a string it will be passed to the shell
396(as with :func:`os.system`).
397
398These methods do not make it possible to retrieve the exit status from the child
399processes. The only way to control the input and output streams and also
400retrieve the return codes is to use the :mod:`subprocess` module; these are only
401available on Unix.
402
403For a discussion of possible deadlock conditions related to the use of these
404functions, see :ref:`popen2-flow-control`.
405
406
407.. function:: popen2(cmd[, mode[, bufsize]])
408
Georg Brandlf725b952008-01-05 19:44:22 +0000409 Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000410 child_stdout)``.
411
412 .. deprecated:: 2.6
413 All of the :func:`popen\*` functions are obsolete. Use the :mod:`subprocess`
414 module.
415
416 Availability: Macintosh, Unix, Windows.
417
418 .. versionadded:: 2.0
419
420
421.. function:: popen3(cmd[, mode[, bufsize]])
422
Georg Brandlf725b952008-01-05 19:44:22 +0000423 Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000424 child_stdout, child_stderr)``.
425
426 .. deprecated:: 2.6
427 All of the :func:`popen\*` functions are obsolete. Use the :mod:`subprocess`
428 module.
429
430 Availability: Macintosh, Unix, Windows.
431
432 .. versionadded:: 2.0
433
434
435.. function:: popen4(cmd[, mode[, bufsize]])
436
Georg Brandlf725b952008-01-05 19:44:22 +0000437 Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000438 child_stdout_and_stderr)``.
439
440 .. deprecated:: 2.6
441 All of the :func:`popen\*` functions are obsolete. Use the :mod:`subprocess`
442 module.
443
444 Availability: Macintosh, Unix, Windows.
445
446 .. versionadded:: 2.0
447
448(Note that ``child_stdin, child_stdout, and child_stderr`` are named from the
449point of view of the child process, so *child_stdin* is the child's standard
450input.)
451
452This functionality is also available in the :mod:`popen2` module using functions
453of the same names, but the return values of those functions have a different
454order.
455
456
457.. _os-fd-ops:
458
459File Descriptor Operations
460--------------------------
461
462These functions operate on I/O streams referenced using file descriptors.
463
464File descriptors are small integers corresponding to a file that has been opened
465by the current process. For example, standard input is usually file descriptor
4660, standard output is 1, and standard error is 2. Further files opened by a
467process will then be assigned 3, 4, 5, and so forth. The name "file descriptor"
468is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
469by file descriptors.
470
471
472.. function:: close(fd)
473
474 Close file descriptor *fd*. Availability: Macintosh, Unix, Windows.
475
476 .. note::
477
478 This function is intended for low-level I/O and must be applied to a file
479 descriptor as returned by :func:`open` or :func:`pipe`. To close a "file
480 object" returned by the built-in function :func:`open` or by :func:`popen` or
481 :func:`fdopen`, use its :meth:`close` method.
482
483
484.. function:: dup(fd)
485
486 Return a duplicate of file descriptor *fd*. Availability: Macintosh, Unix,
487 Windows.
488
489
490.. function:: dup2(fd, fd2)
491
492 Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary.
493 Availability: Macintosh, Unix, Windows.
494
495
Christian Heimes36281872007-11-30 21:11:28 +0000496.. function:: fchmod(fd, mode)
497
498 Change the mode of the file given by *fd* to the numeric *mode*. See the docs
499 for :func:`chmod` for possible values of *mode*. Availability: Unix.
500
Georg Brandl81ddc1a2007-11-30 22:04:45 +0000501 .. versionadded:: 2.6
502
Christian Heimes36281872007-11-30 21:11:28 +0000503
504.. function:: fchown(fd, uid, gid)
505
506 Change the owner and group id of the file given by *fd* to the numeric *uid*
507 and *gid*. To leave one of the ids unchanged, set it to -1.
508 Availability: Unix.
509
Georg Brandl81ddc1a2007-11-30 22:04:45 +0000510 .. versionadded:: 2.6
511
Christian Heimes36281872007-11-30 21:11:28 +0000512
Georg Brandl8ec7f652007-08-15 14:28:01 +0000513.. function:: fdatasync(fd)
514
515 Force write of file with filedescriptor *fd* to disk. Does not force update of
516 metadata. Availability: Unix.
517
518
519.. function:: fpathconf(fd, name)
520
521 Return system configuration information relevant to an open file. *name*
522 specifies the configuration value to retrieve; it may be a string which is the
523 name of a defined system value; these names are specified in a number of
524 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
525 additional names as well. The names known to the host operating system are
526 given in the ``pathconf_names`` dictionary. For configuration variables not
527 included in that mapping, passing an integer for *name* is also accepted.
528 Availability: Macintosh, Unix.
529
530 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
531 specific value for *name* is not supported by the host system, even if it is
532 included in ``pathconf_names``, an :exc:`OSError` is raised with
533 :const:`errno.EINVAL` for the error number.
534
535
536.. function:: fstat(fd)
537
538 Return status for file descriptor *fd*, like :func:`stat`. Availability:
539 Macintosh, Unix, Windows.
540
541
542.. function:: fstatvfs(fd)
543
544 Return information about the filesystem containing the file associated with file
545 descriptor *fd*, like :func:`statvfs`. Availability: Unix.
546
547
548.. function:: fsync(fd)
549
550 Force write of file with filedescriptor *fd* to disk. On Unix, this calls the
551 native :cfunc:`fsync` function; on Windows, the MS :cfunc:`_commit` function.
552
553 If you're starting with a Python file object *f*, first do ``f.flush()``, and
554 then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated
555 with *f* are written to disk. Availability: Macintosh, Unix, and Windows
556 starting in 2.2.3.
557
558
559.. function:: ftruncate(fd, length)
560
561 Truncate the file corresponding to file descriptor *fd*, so that it is at most
562 *length* bytes in size. Availability: Macintosh, Unix.
563
564
565.. function:: isatty(fd)
566
567 Return ``True`` if the file descriptor *fd* is open and connected to a
568 tty(-like) device, else ``False``. Availability: Macintosh, Unix.
569
570
571.. function:: lseek(fd, pos, how)
572
Georg Brandlf725b952008-01-05 19:44:22 +0000573 Set the current position of file descriptor *fd* to position *pos*, modified
574 by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the
575 beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the
576 current position; :const:`os.SEEK_END` or ``2`` to set it relative to the end of
Georg Brandl8ec7f652007-08-15 14:28:01 +0000577 the file. Availability: Macintosh, Unix, Windows.
578
579
580.. function:: open(file, flags[, mode])
581
582 Open the file *file* and set various flags according to *flags* and possibly its
583 mode according to *mode*. The default *mode* is ``0777`` (octal), and the
584 current umask value is first masked out. Return the file descriptor for the
585 newly opened file. Availability: Macintosh, Unix, Windows.
586
587 For a description of the flag and mode values, see the C run-time documentation;
588 flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
589 this module too (see below).
590
591 .. note::
592
593 This function is intended for low-level I/O. For normal usage, use the built-in
594 function :func:`open`, which returns a "file object" with :meth:`read` and
595 :meth:`write` methods (and many more). To wrap a file descriptor in a "file
596 object", use :func:`fdopen`.
597
598
599.. function:: openpty()
600
601 .. index:: module: pty
602
603 Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master,
604 slave)`` for the pty and the tty, respectively. For a (slightly) more portable
Georg Brandlf725b952008-01-05 19:44:22 +0000605 approach, use the :mod:`pty` module. Availability: Macintosh, some flavors of
Georg Brandl8ec7f652007-08-15 14:28:01 +0000606 Unix.
607
608
609.. function:: pipe()
610
611 Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading
612 and writing, respectively. Availability: Macintosh, Unix, Windows.
613
614
615.. function:: read(fd, n)
616
617 Read at most *n* bytes from file descriptor *fd*. Return a string containing the
618 bytes read. If the end of the file referred to by *fd* has been reached, an
619 empty string is returned. Availability: Macintosh, Unix, Windows.
620
621 .. note::
622
623 This function is intended for low-level I/O and must be applied to a file
624 descriptor as returned by :func:`open` or :func:`pipe`. To read a "file object"
625 returned by the built-in function :func:`open` or by :func:`popen` or
Georg Brandlf725b952008-01-05 19:44:22 +0000626 :func:`fdopen`, or :data:`sys.stdin`, use its :meth:`read` or :meth:`readline`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000627 methods.
628
629
630.. function:: tcgetpgrp(fd)
631
632 Return the process group associated with the terminal given by *fd* (an open
633 file descriptor as returned by :func:`open`). Availability: Macintosh, Unix.
634
635
636.. function:: tcsetpgrp(fd, pg)
637
638 Set the process group associated with the terminal given by *fd* (an open file
639 descriptor as returned by :func:`open`) to *pg*. Availability: Macintosh, Unix.
640
641
642.. function:: ttyname(fd)
643
644 Return a string which specifies the terminal device associated with
Georg Brandlbb75e4e2007-10-21 10:46:24 +0000645 file descriptor *fd*. If *fd* is not associated with a terminal device, an
Georg Brandl8ec7f652007-08-15 14:28:01 +0000646 exception is raised. Availability:Macintosh, Unix.
647
648
649.. function:: write(fd, str)
650
651 Write the string *str* to file descriptor *fd*. Return the number of bytes
652 actually written. Availability: Macintosh, Unix, Windows.
653
654 .. note::
655
656 This function is intended for low-level I/O and must be applied to a file
657 descriptor as returned by :func:`open` or :func:`pipe`. To write a "file
658 object" returned by the built-in function :func:`open` or by :func:`popen` or
Georg Brandlf725b952008-01-05 19:44:22 +0000659 :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its :meth:`write`
Georg Brandl8ec7f652007-08-15 14:28:01 +0000660 method.
661
662The following data items are available for use in constructing the *flags*
663parameter to the :func:`open` function. Some items will not be available on all
664platforms. For descriptions of their availability and use, consult
665:manpage:`open(2)`.
666
667
668.. data:: O_RDONLY
669 O_WRONLY
670 O_RDWR
671 O_APPEND
672 O_CREAT
673 O_EXCL
674 O_TRUNC
675
676 Options for the *flag* argument to the :func:`open` function. These can be
Georg Brandlf725b952008-01-05 19:44:22 +0000677 combined using the bitwise OR operator ``|``. Availability: Macintosh, Unix, Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000678
679
680.. data:: O_DSYNC
681 O_RSYNC
682 O_SYNC
683 O_NDELAY
684 O_NONBLOCK
685 O_NOCTTY
686 O_SHLOCK
687 O_EXLOCK
688
689 More options for the *flag* argument to the :func:`open` function. Availability:
690 Macintosh, Unix.
691
692
693.. data:: O_BINARY
Georg Brandlb67da6e2007-11-24 13:56:09 +0000694 O_NOINHERIT
Georg Brandl8ec7f652007-08-15 14:28:01 +0000695 O_SHORT_LIVED
696 O_TEMPORARY
697 O_RANDOM
698 O_SEQUENTIAL
699 O_TEXT
700
701 Options for the *flag* argument to the :func:`open` function. These can be
Georg Brandlf725b952008-01-05 19:44:22 +0000702 combined using the bitwise OR operator ``|``. Availability: Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000703
704
Georg Brandlb67da6e2007-11-24 13:56:09 +0000705.. data:: O_DIRECT
706 O_DIRECTORY
707 O_NOFOLLOW
708 O_NOATIME
709
710 Options for the *flag* argument to the :func:`open` function. These are
711 GNU extensions and not present if they are not defined by the C library.
712
713
Georg Brandl8ec7f652007-08-15 14:28:01 +0000714.. data:: SEEK_SET
715 SEEK_CUR
716 SEEK_END
717
718 Parameters to the :func:`lseek` function. Their values are 0, 1, and 2,
719 respectively. Availability: Windows, Macintosh, Unix.
720
721 .. versionadded:: 2.5
722
723
724.. _os-file-dir:
725
726Files and Directories
727---------------------
728
Georg Brandl8ec7f652007-08-15 14:28:01 +0000729.. function:: access(path, mode)
730
731 Use the real uid/gid to test for access to *path*. Note that most operations
732 will use the effective uid/gid, therefore this routine can be used in a
733 suid/sgid environment to test if the invoking user has the specified access to
734 *path*. *mode* should be :const:`F_OK` to test the existence of *path*, or it
735 can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and
736 :const:`X_OK` to test permissions. Return :const:`True` if access is allowed,
737 :const:`False` if not. See the Unix man page :manpage:`access(2)` for more
738 information. Availability: Macintosh, Unix, Windows.
739
740 .. note::
741
742 Using :func:`access` to check if a user is authorized to e.g. open a file before
743 actually doing so using :func:`open` creates a security hole, because the user
744 might exploit the short time interval between checking and opening the file to
745 manipulate it.
746
747 .. note::
748
749 I/O operations may fail even when :func:`access` indicates that they would
750 succeed, particularly for operations on network filesystems which may have
751 permissions semantics beyond the usual POSIX permission-bit model.
752
753
754.. data:: F_OK
755
756 Value to pass as the *mode* parameter of :func:`access` to test the existence of
757 *path*.
758
759
760.. data:: R_OK
761
762 Value to include in the *mode* parameter of :func:`access` to test the
763 readability of *path*.
764
765
766.. data:: W_OK
767
768 Value to include in the *mode* parameter of :func:`access` to test the
769 writability of *path*.
770
771
772.. data:: X_OK
773
774 Value to include in the *mode* parameter of :func:`access` to determine if
775 *path* can be executed.
776
777
778.. function:: chdir(path)
779
780 .. index:: single: directory; changing
781
782 Change the current working directory to *path*. Availability: Macintosh, Unix,
783 Windows.
784
785
786.. function:: fchdir(fd)
787
788 Change the current working directory to the directory represented by the file
789 descriptor *fd*. The descriptor must refer to an opened directory, not an open
790 file. Availability: Unix.
791
792 .. versionadded:: 2.3
793
794
795.. function:: getcwd()
796
797 Return a string representing the current working directory. Availability:
798 Macintosh, Unix, Windows.
799
800
801.. function:: getcwdu()
802
803 Return a Unicode object representing the current working directory.
804 Availability: Macintosh, Unix, Windows.
805
806 .. versionadded:: 2.3
807
808
809.. function:: chflags(path, flags)
810
811 Set the flags of *path* to the numeric *flags*. *flags* may take a combination
812 (bitwise OR) of the following values (as defined in the :mod:`stat` module):
813
814 * ``UF_NODUMP``
815 * ``UF_IMMUTABLE``
816 * ``UF_APPEND``
817 * ``UF_OPAQUE``
818 * ``UF_NOUNLINK``
819 * ``SF_ARCHIVED``
820 * ``SF_IMMUTABLE``
821 * ``SF_APPEND``
822 * ``SF_NOUNLINK``
823 * ``SF_SNAPSHOT``
824
825 Availability: Macintosh, Unix.
826
827 .. versionadded:: 2.6
828
829
830.. function:: chroot(path)
831
832 Change the root directory of the current process to *path*. Availability:
833 Macintosh, Unix.
834
835 .. versionadded:: 2.2
836
837
838.. function:: chmod(path, mode)
839
840 Change the mode of *path* to the numeric *mode*. *mode* may take one of the
Georg Brandlf725b952008-01-05 19:44:22 +0000841 following values (as defined in the :mod:`stat` module) or bitwise ORed
Georg Brandl8ec7f652007-08-15 14:28:01 +0000842 combinations of them:
843
844
845 * ``stat.S_ISUID``
846 * ``stat.S_ISGID``
847 * ``stat.S_ENFMT``
848 * ``stat.S_ISVTX``
849 * ``stat.S_IREAD``
850 * ``stat.S_IWRITE``
851 * ``stat.S_IEXEC``
852 * ``stat.S_IRWXU``
853 * ``stat.S_IRUSR``
854 * ``stat.S_IWUSR``
855 * ``stat.S_IXUSR``
856 * ``stat.S_IRWXG``
857 * ``stat.S_IRGRP``
858 * ``stat.S_IWGRP``
859 * ``stat.S_IXGRP``
860 * ``stat.S_IRWXO``
861 * ``stat.S_IROTH``
862 * ``stat.S_IWOTH``
863 * ``stat.S_IXOTH``
864
865 Availability: Macintosh, Unix, Windows.
866
867 .. note::
868
869 Although Windows supports :func:`chmod`, you can only set the file's read-only
870 flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD``
871 constants or a corresponding integer value). All other bits are
872 ignored.
873
874
875.. function:: chown(path, uid, gid)
876
877 Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave
878 one of the ids unchanged, set it to -1. Availability: Macintosh, Unix.
879
880
881.. function:: lchflags(path, flags)
882
883 Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not
884 follow symbolic links. Availability: Unix.
885
886 .. versionadded:: 2.6
887
888
Georg Brandl81ddc1a2007-11-30 22:04:45 +0000889.. function:: lchmod(path, mode)
890
891 Change the mode of *path* to the numeric *mode*. If path is a symlink, this
892 affects the symlink rather than the target. See the docs for :func:`chmod`
893 for possible values of *mode*. Availability: Unix.
894
895 .. versionadded:: 2.6
896
897
Georg Brandl8ec7f652007-08-15 14:28:01 +0000898.. function:: lchown(path, uid, gid)
899
Georg Brandlf725b952008-01-05 19:44:22 +0000900 Change the owner and group id of *path* to the numeric *uid* and *gid*. This
Georg Brandl8ec7f652007-08-15 14:28:01 +0000901 function will not follow symbolic links. Availability: Macintosh, Unix.
902
903 .. versionadded:: 2.3
904
905
906.. function:: link(src, dst)
907
908 Create a hard link pointing to *src* named *dst*. Availability: Macintosh, Unix.
909
910
911.. function:: listdir(path)
912
913 Return a list containing the names of the entries in the directory. The list is
914 in arbitrary order. It does not include the special entries ``'.'`` and
915 ``'..'`` even if they are present in the directory. Availability: Macintosh,
916 Unix, Windows.
917
918 .. versionchanged:: 2.3
919 On Windows NT/2k/XP and Unix, if *path* is a Unicode object, the result will be
920 a list of Unicode objects.
921
922
923.. function:: lstat(path)
924
Georg Brandl03b15c62007-11-01 17:19:33 +0000925 Like :func:`stat`, but do not follow symbolic links. This is an alias for
926 :func:`stat` on platforms that do not support symbolic links, such as
927 Windows.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000928
929
930.. function:: mkfifo(path[, mode])
931
932 Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The default
933 *mode* is ``0666`` (octal). The current umask value is first masked out from
934 the mode. Availability: Macintosh, Unix.
935
936 FIFOs are pipes that can be accessed like regular files. FIFOs exist until they
937 are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
938 rendezvous between "client" and "server" type processes: the server opens the
939 FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo`
940 doesn't open the FIFO --- it just creates the rendezvous point.
941
942
943.. function:: mknod(filename[, mode=0600, device])
944
945 Create a filesystem node (file, device special file or named pipe) named
946 *filename*. *mode* specifies both the permissions to use and the type of node to
947 be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
948 ``stat.S_IFCHR``, ``stat.S_IFBLK``,
949 and ``stat.S_IFIFO`` (those constants are available in :mod:`stat`).
950 For ``stat.S_IFCHR`` and
951 ``stat.S_IFBLK``, *device* defines the newly created device special file (probably using
952 :func:`os.makedev`), otherwise it is ignored.
953
954 .. versionadded:: 2.3
955
956
957.. function:: major(device)
958
Georg Brandlf725b952008-01-05 19:44:22 +0000959 Extract the device major number from a raw device number (usually the
Georg Brandl8ec7f652007-08-15 14:28:01 +0000960 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
961
962 .. versionadded:: 2.3
963
964
965.. function:: minor(device)
966
Georg Brandlf725b952008-01-05 19:44:22 +0000967 Extract the device minor number from a raw device number (usually the
Georg Brandl8ec7f652007-08-15 14:28:01 +0000968 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
969
970 .. versionadded:: 2.3
971
972
973.. function:: makedev(major, minor)
974
Georg Brandlf725b952008-01-05 19:44:22 +0000975 Compose a raw device number from the major and minor device numbers.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000976
977 .. versionadded:: 2.3
978
979
980.. function:: mkdir(path[, mode])
981
982 Create a directory named *path* with numeric mode *mode*. The default *mode* is
983 ``0777`` (octal). On some systems, *mode* is ignored. Where it is used, the
984 current umask value is first masked out. Availability: Macintosh, Unix, Windows.
985
Mark Summerfieldac3d4292007-11-02 08:24:59 +0000986 It is also possible to create temporary directories; see the
987 :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
988
Georg Brandl8ec7f652007-08-15 14:28:01 +0000989
990.. function:: makedirs(path[, mode])
991
992 .. index::
993 single: directory; creating
994 single: UNC paths; and os.makedirs()
995
996 Recursive directory creation function. Like :func:`mkdir`, but makes all
997 intermediate-level directories needed to contain the leaf directory. Throws an
998 :exc:`error` exception if the leaf directory already exists or cannot be
999 created. The default *mode* is ``0777`` (octal). On some systems, *mode* is
1000 ignored. Where it is used, the current umask value is first masked out.
1001
1002 .. note::
1003
1004 :func:`makedirs` will become confused if the path elements to create include
Georg Brandlf725b952008-01-05 19:44:22 +00001005 :data:`os.pardir`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001006
1007 .. versionadded:: 1.5.2
1008
1009 .. versionchanged:: 2.3
1010 This function now handles UNC paths correctly.
1011
1012
1013.. function:: pathconf(path, name)
1014
1015 Return system configuration information relevant to a named file. *name*
1016 specifies the configuration value to retrieve; it may be a string which is the
1017 name of a defined system value; these names are specified in a number of
1018 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
1019 additional names as well. The names known to the host operating system are
1020 given in the ``pathconf_names`` dictionary. For configuration variables not
1021 included in that mapping, passing an integer for *name* is also accepted.
1022 Availability: Macintosh, Unix.
1023
1024 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
1025 specific value for *name* is not supported by the host system, even if it is
1026 included in ``pathconf_names``, an :exc:`OSError` is raised with
1027 :const:`errno.EINVAL` for the error number.
1028
1029
1030.. data:: pathconf_names
1031
1032 Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
1033 the integer values defined for those names by the host operating system. This
1034 can be used to determine the set of names known to the system. Availability:
1035 Macintosh, Unix.
1036
1037
1038.. function:: readlink(path)
1039
1040 Return a string representing the path to which the symbolic link points. The
1041 result may be either an absolute or relative pathname; if it is relative, it may
1042 be converted to an absolute pathname using ``os.path.join(os.path.dirname(path),
1043 result)``.
1044
1045 .. versionchanged:: 2.6
1046 If the *path* is a Unicode object the result will also be a Unicode object.
1047
1048 Availability: Macintosh, Unix.
1049
1050
1051.. function:: remove(path)
1052
1053 Remove the file *path*. If *path* is a directory, :exc:`OSError` is raised; see
1054 :func:`rmdir` below to remove a directory. This is identical to the
1055 :func:`unlink` function documented below. On Windows, attempting to remove a
1056 file that is in use causes an exception to be raised; on Unix, the directory
1057 entry is removed but the storage allocated to the file is not made available
1058 until the original file is no longer in use. Availability: Macintosh, Unix,
1059 Windows.
1060
1061
1062.. function:: removedirs(path)
1063
1064 .. index:: single: directory; deleting
1065
Georg Brandlf725b952008-01-05 19:44:22 +00001066 Remove directories recursively. Works like :func:`rmdir` except that, if the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001067 leaf directory is successfully removed, :func:`removedirs` tries to
1068 successively remove every parent directory mentioned in *path* until an error
1069 is raised (which is ignored, because it generally means that a parent directory
1070 is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
1071 the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
1072 they are empty. Raises :exc:`OSError` if the leaf directory could not be
1073 successfully removed.
1074
1075 .. versionadded:: 1.5.2
1076
1077
1078.. function:: rename(src, dst)
1079
1080 Rename the file or directory *src* to *dst*. If *dst* is a directory,
1081 :exc:`OSError` will be raised. On Unix, if *dst* exists and is a file, it will
Georg Brandlf725b952008-01-05 19:44:22 +00001082 be replaced silently if the user has permission. The operation may fail on some
Georg Brandl8ec7f652007-08-15 14:28:01 +00001083 Unix flavors if *src* and *dst* are on different filesystems. If successful,
1084 the renaming will be an atomic operation (this is a POSIX requirement). On
1085 Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a
1086 file; there may be no way to implement an atomic rename when *dst* names an
1087 existing file. Availability: Macintosh, Unix, Windows.
1088
1089
1090.. function:: renames(old, new)
1091
1092 Recursive directory or file renaming function. Works like :func:`rename`, except
1093 creation of any intermediate directories needed to make the new pathname good is
1094 attempted first. After the rename, directories corresponding to rightmost path
1095 segments of the old name will be pruned away using :func:`removedirs`.
1096
1097 .. versionadded:: 1.5.2
1098
1099 .. note::
1100
1101 This function can fail with the new directory structure made if you lack
1102 permissions needed to remove the leaf directory or file.
1103
1104
1105.. function:: rmdir(path)
1106
1107 Remove the directory *path*. Availability: Macintosh, Unix, Windows.
1108
1109
1110.. function:: stat(path)
1111
1112 Perform a :cfunc:`stat` system call on the given path. The return value is an
1113 object whose attributes correspond to the members of the :ctype:`stat`
1114 structure, namely: :attr:`st_mode` (protection bits), :attr:`st_ino` (inode
1115 number), :attr:`st_dev` (device), :attr:`st_nlink` (number of hard links),
Georg Brandlf725b952008-01-05 19:44:22 +00001116 :attr:`st_uid` (user id of owner), :attr:`st_gid` (group id of owner),
Georg Brandl8ec7f652007-08-15 14:28:01 +00001117 :attr:`st_size` (size of file, in bytes), :attr:`st_atime` (time of most recent
1118 access), :attr:`st_mtime` (time of most recent content modification),
1119 :attr:`st_ctime` (platform dependent; time of most recent metadata change on
1120 Unix, or the time of creation on Windows)::
1121
1122 >>> import os
1123 >>> statinfo = os.stat('somefile.txt')
1124 >>> statinfo
1125 (33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
1126 >>> statinfo.st_size
1127 926L
1128 >>>
1129
1130 .. versionchanged:: 2.3
Georg Brandlf725b952008-01-05 19:44:22 +00001131 If :func:`stat_float_times` returns ``True``, the time values are floats, measuring
Georg Brandl8ec7f652007-08-15 14:28:01 +00001132 seconds. Fractions of a second may be reported if the system supports that. On
1133 Mac OS, the times are always floats. See :func:`stat_float_times` for further
1134 discussion.
1135
1136 On some Unix systems (such as Linux), the following attributes may also be
1137 available: :attr:`st_blocks` (number of blocks allocated for file),
1138 :attr:`st_blksize` (filesystem blocksize), :attr:`st_rdev` (type of device if an
1139 inode device). :attr:`st_flags` (user defined flags for file).
1140
1141 On other Unix systems (such as FreeBSD), the following attributes may be
1142 available (but may be only filled out if root tries to use them): :attr:`st_gen`
1143 (file generation number), :attr:`st_birthtime` (time of file creation).
1144
1145 On Mac OS systems, the following attributes may also be available:
1146 :attr:`st_rsize`, :attr:`st_creator`, :attr:`st_type`.
1147
1148 On RISCOS systems, the following attributes are also available: :attr:`st_ftype`
1149 (file type), :attr:`st_attrs` (attributes), :attr:`st_obtype` (object type).
1150
1151 .. index:: module: stat
1152
1153 For backward compatibility, the return value of :func:`stat` is also accessible
1154 as a tuple of at least 10 integers giving the most important (and portable)
1155 members of the :ctype:`stat` structure, in the order :attr:`st_mode`,
1156 :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, :attr:`st_uid`,
1157 :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, :attr:`st_mtime`,
1158 :attr:`st_ctime`. More items may be added at the end by some implementations.
1159 The standard module :mod:`stat` defines functions and constants that are useful
1160 for extracting information from a :ctype:`stat` structure. (On Windows, some
1161 items are filled with dummy values.)
1162
1163 .. note::
1164
1165 The exact meaning and resolution of the :attr:`st_atime`, :attr:`st_mtime`, and
1166 :attr:`st_ctime` members depends on the operating system and the file system.
1167 For example, on Windows systems using the FAT or FAT32 file systems,
1168 :attr:`st_mtime` has 2-second resolution, and :attr:`st_atime` has only 1-day
1169 resolution. See your operating system documentation for details.
1170
1171 Availability: Macintosh, Unix, Windows.
1172
1173 .. versionchanged:: 2.2
1174 Added access to values as attributes of the returned object.
1175
1176 .. versionchanged:: 2.5
Georg Brandlf725b952008-01-05 19:44:22 +00001177 Added :attr:`st_gen` and :attr:`st_birthtime`.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001178
1179
1180.. function:: stat_float_times([newvalue])
1181
1182 Determine whether :class:`stat_result` represents time stamps as float objects.
1183 If *newvalue* is ``True``, future calls to :func:`stat` return floats, if it is
1184 ``False``, future calls return ints. If *newvalue* is omitted, return the
1185 current setting.
1186
1187 For compatibility with older Python versions, accessing :class:`stat_result` as
1188 a tuple always returns integers.
1189
1190 .. versionchanged:: 2.5
1191 Python now returns float values by default. Applications which do not work
1192 correctly with floating point time stamps can use this function to restore the
1193 old behaviour.
1194
1195 The resolution of the timestamps (that is the smallest possible fraction)
1196 depends on the system. Some systems only support second resolution; on these
1197 systems, the fraction will always be zero.
1198
1199 It is recommended that this setting is only changed at program startup time in
1200 the *__main__* module; libraries should never change this setting. If an
1201 application uses a library that works incorrectly if floating point time stamps
1202 are processed, this application should turn the feature off until the library
1203 has been corrected.
1204
1205
1206.. function:: statvfs(path)
1207
1208 Perform a :cfunc:`statvfs` system call on the given path. The return value is
1209 an object whose attributes describe the filesystem on the given path, and
1210 correspond to the members of the :ctype:`statvfs` structure, namely:
1211 :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
1212 :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
1213 :attr:`f_flag`, :attr:`f_namemax`. Availability: Unix.
1214
1215 .. index:: module: statvfs
1216
1217 For backward compatibility, the return value is also accessible as a tuple whose
1218 values correspond to the attributes, in the order given above. The standard
1219 module :mod:`statvfs` defines constants that are useful for extracting
1220 information from a :ctype:`statvfs` structure when accessing it as a sequence;
1221 this remains useful when writing code that needs to work with versions of Python
1222 that don't support accessing the fields as attributes.
1223
1224 .. versionchanged:: 2.2
1225 Added access to values as attributes of the returned object.
1226
1227
1228.. function:: symlink(src, dst)
1229
1230 Create a symbolic link pointing to *src* named *dst*. Availability: Unix.
1231
1232
1233.. function:: tempnam([dir[, prefix]])
1234
1235 Return a unique path name that is reasonable for creating a temporary file.
1236 This will be an absolute path that names a potential directory entry in the
1237 directory *dir* or a common location for temporary files if *dir* is omitted or
1238 ``None``. If given and not ``None``, *prefix* is used to provide a short prefix
1239 to the filename. Applications are responsible for properly creating and
1240 managing files created using paths returned by :func:`tempnam`; no automatic
1241 cleanup is provided. On Unix, the environment variable :envvar:`TMPDIR`
Georg Brandlf725b952008-01-05 19:44:22 +00001242 overrides *dir*, while on Windows :envvar:`TMP` is used. The specific
Georg Brandl8ec7f652007-08-15 14:28:01 +00001243 behavior of this function depends on the C library implementation; some aspects
1244 are underspecified in system documentation.
1245
1246 .. warning::
1247
1248 Use of :func:`tempnam` is vulnerable to symlink attacks; consider using
1249 :func:`tmpfile` (section :ref:`os-newstreams`) instead.
1250
1251 Availability: Macintosh, Unix, Windows.
1252
1253
1254.. function:: tmpnam()
1255
1256 Return a unique path name that is reasonable for creating a temporary file.
1257 This will be an absolute path that names a potential directory entry in a common
1258 location for temporary files. Applications are responsible for properly
1259 creating and managing files created using paths returned by :func:`tmpnam`; no
1260 automatic cleanup is provided.
1261
1262 .. warning::
1263
1264 Use of :func:`tmpnam` is vulnerable to symlink attacks; consider using
1265 :func:`tmpfile` (section :ref:`os-newstreams`) instead.
1266
1267 Availability: Unix, Windows. This function probably shouldn't be used on
1268 Windows, though: Microsoft's implementation of :func:`tmpnam` always creates a
1269 name in the root directory of the current drive, and that's generally a poor
1270 location for a temp file (depending on privileges, you may not even be able to
1271 open a file using this name).
1272
1273
1274.. data:: TMP_MAX
1275
1276 The maximum number of unique names that :func:`tmpnam` will generate before
1277 reusing names.
1278
1279
1280.. function:: unlink(path)
1281
1282 Remove the file *path*. This is the same function as :func:`remove`; the
1283 :func:`unlink` name is its traditional Unix name. Availability: Macintosh, Unix,
1284 Windows.
1285
1286
1287.. function:: utime(path, times)
1288
1289 Set the access and modified times of the file specified by *path*. If *times* is
1290 ``None``, then the file's access and modified times are set to the current time.
1291 Otherwise, *times* must be a 2-tuple of numbers, of the form ``(atime, mtime)``
1292 which is used to set the access and modified times, respectively. Whether a
1293 directory can be given for *path* depends on whether the operating system
1294 implements directories as files (for example, Windows does not). Note that the
1295 exact times you set here may not be returned by a subsequent :func:`stat` call,
1296 depending on the resolution with which your operating system records access and
1297 modification times; see :func:`stat`.
1298
1299 .. versionchanged:: 2.0
1300 Added support for ``None`` for *times*.
1301
1302 Availability: Macintosh, Unix, Windows.
1303
1304
1305.. function:: walk(top[, topdown=True [, onerror=None[, followlinks=False]]])
1306
1307 .. index::
1308 single: directory; walking
1309 single: directory; traversal
1310
Georg Brandlf725b952008-01-05 19:44:22 +00001311 Generate the file names in a directory tree by walking the tree
1312 either top-down or bottom-up. For each directory in the tree rooted at directory
Georg Brandl8ec7f652007-08-15 14:28:01 +00001313 *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
1314 filenames)``.
1315
1316 *dirpath* is a string, the path to the directory. *dirnames* is a list of the
1317 names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``).
1318 *filenames* is a list of the names of the non-directory files in *dirpath*.
1319 Note that the names in the lists contain no path components. To get a full path
1320 (which begins with *top*) to a file or directory in *dirpath*, do
1321 ``os.path.join(dirpath, name)``.
1322
Georg Brandlf725b952008-01-05 19:44:22 +00001323 If optional argument *topdown* is ``True`` or not specified, the triple for a
Georg Brandl8ec7f652007-08-15 14:28:01 +00001324 directory is generated before the triples for any of its subdirectories
Georg Brandlf725b952008-01-05 19:44:22 +00001325 (directories are generated top-down). If *topdown* is ``False``, the triple for a
Georg Brandl8ec7f652007-08-15 14:28:01 +00001326 directory is generated after the triples for all of its subdirectories
Georg Brandlf725b952008-01-05 19:44:22 +00001327 (directories are generated bottom-up).
Georg Brandl8ec7f652007-08-15 14:28:01 +00001328
Georg Brandlf725b952008-01-05 19:44:22 +00001329 When *topdown* is ``True``, the caller can modify the *dirnames* list in-place
Georg Brandl8ec7f652007-08-15 14:28:01 +00001330 (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
1331 recurse into the subdirectories whose names remain in *dirnames*; this can be
1332 used to prune the search, impose a specific order of visiting, or even to inform
1333 :func:`walk` about directories the caller creates or renames before it resumes
Georg Brandlf725b952008-01-05 19:44:22 +00001334 :func:`walk` again. Modifying *dirnames* when *topdown* is ``False`` is
Georg Brandl8ec7f652007-08-15 14:28:01 +00001335 ineffective, because in bottom-up mode the directories in *dirnames* are
1336 generated before *dirpath* itself is generated.
1337
Georg Brandlf725b952008-01-05 19:44:22 +00001338 By default errors from the :func:`listdir` call are ignored. If optional
Georg Brandl8ec7f652007-08-15 14:28:01 +00001339 argument *onerror* is specified, it should be a function; it will be called with
1340 one argument, an :exc:`OSError` instance. It can report the error to continue
1341 with the walk, or raise the exception to abort the walk. Note that the filename
1342 is available as the ``filename`` attribute of the exception object.
1343
1344 By default, :func:`walk` will not walk down into symbolic links that resolve to
Georg Brandlf725b952008-01-05 19:44:22 +00001345 directories. Set *followlinks* to ``True`` to visit directories pointed to by
Georg Brandl8ec7f652007-08-15 14:28:01 +00001346 symlinks, on systems that support them.
1347
1348 .. versionadded:: 2.6
1349 The *followlinks* parameter.
1350
1351 .. note::
1352
Georg Brandlf725b952008-01-05 19:44:22 +00001353 Be aware that setting *followlinks* to ``True`` can lead to infinite recursion if a
Georg Brandl8ec7f652007-08-15 14:28:01 +00001354 link points to a parent directory of itself. :func:`walk` does not keep track of
1355 the directories it visited already.
1356
1357 .. note::
1358
1359 If you pass a relative pathname, don't change the current working directory
1360 between resumptions of :func:`walk`. :func:`walk` never changes the current
1361 directory, and assumes that its caller doesn't either.
1362
1363 This example displays the number of bytes taken by non-directory files in each
1364 directory under the starting directory, except that it doesn't look under any
1365 CVS subdirectory::
1366
1367 import os
1368 from os.path import join, getsize
1369 for root, dirs, files in os.walk('python/Lib/email'):
1370 print root, "consumes",
1371 print sum(getsize(join(root, name)) for name in files),
1372 print "bytes in", len(files), "non-directory files"
1373 if 'CVS' in dirs:
1374 dirs.remove('CVS') # don't visit CVS directories
1375
Georg Brandlf725b952008-01-05 19:44:22 +00001376 In the next example, walking the tree bottom-up is essential: :func:`rmdir`
Georg Brandl8ec7f652007-08-15 14:28:01 +00001377 doesn't allow deleting a directory before the directory is empty::
1378
Georg Brandlf725b952008-01-05 19:44:22 +00001379 # Delete everything reachable from the directory named in "top",
Georg Brandl8ec7f652007-08-15 14:28:01 +00001380 # assuming there are no symbolic links.
1381 # CAUTION: This is dangerous! For example, if top == '/', it
1382 # could delete all your disk files.
1383 import os
1384 for root, dirs, files in os.walk(top, topdown=False):
1385 for name in files:
1386 os.remove(os.path.join(root, name))
1387 for name in dirs:
1388 os.rmdir(os.path.join(root, name))
1389
1390 .. versionadded:: 2.3
1391
1392
1393.. _os-process:
1394
1395Process Management
1396------------------
1397
1398These functions may be used to create and manage processes.
1399
1400The various :func:`exec\*` functions take a list of arguments for the new
1401program loaded into the process. In each case, the first of these arguments is
1402passed to the new program as its own name rather than as an argument a user may
1403have typed on a command line. For the C programmer, this is the ``argv[0]``
1404passed to a program's :cfunc:`main`. For example, ``os.execv('/bin/echo',
1405['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
1406to be ignored.
1407
1408
1409.. function:: abort()
1410
1411 Generate a :const:`SIGABRT` signal to the current process. On Unix, the default
1412 behavior is to produce a core dump; on Windows, the process immediately returns
1413 an exit code of ``3``. Be aware that programs which use :func:`signal.signal`
1414 to register a handler for :const:`SIGABRT` will behave differently.
1415 Availability: Macintosh, Unix, Windows.
1416
1417
1418.. function:: execl(path, arg0, arg1, ...)
1419 execle(path, arg0, arg1, ..., env)
1420 execlp(file, arg0, arg1, ...)
1421 execlpe(file, arg0, arg1, ..., env)
1422 execv(path, args)
1423 execve(path, args, env)
1424 execvp(file, args)
1425 execvpe(file, args, env)
1426
1427 These functions all execute a new program, replacing the current process; they
1428 do not return. On Unix, the new executable is loaded into the current process,
Georg Brandlf725b952008-01-05 19:44:22 +00001429 and will have the same process id as the caller. Errors will be reported as
Georg Brandl8ec7f652007-08-15 14:28:01 +00001430 :exc:`OSError` exceptions.
1431
Georg Brandlf725b952008-01-05 19:44:22 +00001432 The "l" and "v" variants of the :func:`exec\*` functions differ in how
1433 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl8ec7f652007-08-15 14:28:01 +00001434 to work with if the number of parameters is fixed when the code is written; the
1435 individual parameters simply become additional parameters to the :func:`execl\*`
Georg Brandlf725b952008-01-05 19:44:22 +00001436 functions. The "v" variants are good when the number of parameters is
Georg Brandl8ec7f652007-08-15 14:28:01 +00001437 variable, with the arguments being passed in a list or tuple as the *args*
1438 parameter. In either case, the arguments to the child process should start with
1439 the name of the command being run, but this is not enforced.
1440
Georg Brandlf725b952008-01-05 19:44:22 +00001441 The variants which include a "p" near the end (:func:`execlp`,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001442 :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
1443 :envvar:`PATH` environment variable to locate the program *file*. When the
1444 environment is being replaced (using one of the :func:`exec\*e` variants,
1445 discussed in the next paragraph), the new environment is used as the source of
1446 the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
1447 :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
1448 locate the executable; *path* must contain an appropriate absolute or relative
1449 path.
1450
1451 For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
Georg Brandlf725b952008-01-05 19:44:22 +00001452 that these all end in "e"), the *env* parameter must be a mapping which is
Georg Brandl8ec7f652007-08-15 14:28:01 +00001453 used to define the environment variables for the new process; the :func:`execl`,
1454 :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
1455 inherit the environment of the current process. Availability: Macintosh, Unix,
1456 Windows.
1457
1458
1459.. function:: _exit(n)
1460
1461 Exit to the system with status *n*, without calling cleanup handlers, flushing
1462 stdio buffers, etc. Availability: Macintosh, Unix, Windows.
1463
1464 .. note::
1465
1466 The standard way to exit is ``sys.exit(n)``. :func:`_exit` should normally only
1467 be used in the child process after a :func:`fork`.
1468
Georg Brandlf725b952008-01-05 19:44:22 +00001469The following exit codes are defined and can be used with :func:`_exit`,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001470although they are not required. These are typically used for system programs
1471written in Python, such as a mail server's external command delivery program.
1472
1473.. note::
1474
1475 Some of these may not be available on all Unix platforms, since there is some
1476 variation. These constants are defined where they are defined by the underlying
1477 platform.
1478
1479
1480.. data:: EX_OK
1481
1482 Exit code that means no error occurred. Availability: Macintosh, Unix.
1483
1484 .. versionadded:: 2.3
1485
1486
1487.. data:: EX_USAGE
1488
1489 Exit code that means the command was used incorrectly, such as when the wrong
1490 number of arguments are given. Availability: Macintosh, Unix.
1491
1492 .. versionadded:: 2.3
1493
1494
1495.. data:: EX_DATAERR
1496
1497 Exit code that means the input data was incorrect. Availability: Macintosh,
1498 Unix.
1499
1500 .. versionadded:: 2.3
1501
1502
1503.. data:: EX_NOINPUT
1504
1505 Exit code that means an input file did not exist or was not readable.
1506 Availability: Macintosh, Unix.
1507
1508 .. versionadded:: 2.3
1509
1510
1511.. data:: EX_NOUSER
1512
1513 Exit code that means a specified user did not exist. Availability: Macintosh,
1514 Unix.
1515
1516 .. versionadded:: 2.3
1517
1518
1519.. data:: EX_NOHOST
1520
1521 Exit code that means a specified host did not exist. Availability: Macintosh,
1522 Unix.
1523
1524 .. versionadded:: 2.3
1525
1526
1527.. data:: EX_UNAVAILABLE
1528
1529 Exit code that means that a required service is unavailable. Availability:
1530 Macintosh, Unix.
1531
1532 .. versionadded:: 2.3
1533
1534
1535.. data:: EX_SOFTWARE
1536
1537 Exit code that means an internal software error was detected. Availability:
1538 Macintosh, Unix.
1539
1540 .. versionadded:: 2.3
1541
1542
1543.. data:: EX_OSERR
1544
1545 Exit code that means an operating system error was detected, such as the
1546 inability to fork or create a pipe. Availability: Macintosh, Unix.
1547
1548 .. versionadded:: 2.3
1549
1550
1551.. data:: EX_OSFILE
1552
1553 Exit code that means some system file did not exist, could not be opened, or had
1554 some other kind of error. Availability: Macintosh, Unix.
1555
1556 .. versionadded:: 2.3
1557
1558
1559.. data:: EX_CANTCREAT
1560
1561 Exit code that means a user specified output file could not be created.
1562 Availability: Macintosh, Unix.
1563
1564 .. versionadded:: 2.3
1565
1566
1567.. data:: EX_IOERR
1568
1569 Exit code that means that an error occurred while doing I/O on some file.
1570 Availability: Macintosh, Unix.
1571
1572 .. versionadded:: 2.3
1573
1574
1575.. data:: EX_TEMPFAIL
1576
1577 Exit code that means a temporary failure occurred. This indicates something
1578 that may not really be an error, such as a network connection that couldn't be
1579 made during a retryable operation. Availability: Macintosh, Unix.
1580
1581 .. versionadded:: 2.3
1582
1583
1584.. data:: EX_PROTOCOL
1585
1586 Exit code that means that a protocol exchange was illegal, invalid, or not
1587 understood. Availability: Macintosh, Unix.
1588
1589 .. versionadded:: 2.3
1590
1591
1592.. data:: EX_NOPERM
1593
1594 Exit code that means that there were insufficient permissions to perform the
1595 operation (but not intended for file system problems). Availability: Macintosh,
1596 Unix.
1597
1598 .. versionadded:: 2.3
1599
1600
1601.. data:: EX_CONFIG
1602
1603 Exit code that means that some kind of configuration error occurred.
1604 Availability: Macintosh, Unix.
1605
1606 .. versionadded:: 2.3
1607
1608
1609.. data:: EX_NOTFOUND
1610
1611 Exit code that means something like "an entry was not found". Availability:
1612 Macintosh, Unix.
1613
1614 .. versionadded:: 2.3
1615
1616
1617.. function:: fork()
1618
Georg Brandlf725b952008-01-05 19:44:22 +00001619 Fork a child process. Return ``0`` in the child and the child's process id in the
Georg Brandl8ec7f652007-08-15 14:28:01 +00001620 parent. Availability: Macintosh, Unix.
1621
1622
1623.. function:: forkpty()
1624
1625 Fork a child process, using a new pseudo-terminal as the child's controlling
1626 terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
1627 new child's process id in the parent, and *fd* is the file descriptor of the
1628 master end of the pseudo-terminal. For a more portable approach, use the
Georg Brandlf725b952008-01-05 19:44:22 +00001629 :mod:`pty` module. Availability: Macintosh, some flavors of Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001630
1631
1632.. function:: kill(pid, sig)
1633
1634 .. index::
1635 single: process; killing
1636 single: process; signalling
1637
1638 Send signal *sig* to the process *pid*. Constants for the specific signals
1639 available on the host platform are defined in the :mod:`signal` module.
1640 Availability: Macintosh, Unix.
1641
1642
1643.. function:: killpg(pgid, sig)
1644
1645 .. index::
1646 single: process; killing
1647 single: process; signalling
1648
1649 Send the signal *sig* to the process group *pgid*. Availability: Macintosh,
1650 Unix.
1651
1652 .. versionadded:: 2.3
1653
1654
1655.. function:: nice(increment)
1656
1657 Add *increment* to the process's "niceness". Return the new niceness.
1658 Availability: Macintosh, Unix.
1659
1660
1661.. function:: plock(op)
1662
1663 Lock program segments into memory. The value of *op* (defined in
1664 ``<sys/lock.h>``) determines which segments are locked. Availability: Macintosh,
1665 Unix.
1666
1667
1668.. function:: popen(...)
1669 popen2(...)
1670 popen3(...)
1671 popen4(...)
1672 :noindex:
1673
1674 Run child processes, returning opened pipes for communications. These functions
1675 are described in section :ref:`os-newstreams`.
1676
1677
1678.. function:: spawnl(mode, path, ...)
1679 spawnle(mode, path, ..., env)
1680 spawnlp(mode, file, ...)
1681 spawnlpe(mode, file, ..., env)
1682 spawnv(mode, path, args)
1683 spawnve(mode, path, args, env)
1684 spawnvp(mode, file, args)
1685 spawnvpe(mode, file, args, env)
1686
1687 Execute the program *path* in a new process.
1688
1689 (Note that the :mod:`subprocess` module provides more powerful facilities for
1690 spawning new processes and retrieving their results; using that module is
1691 preferable to using these functions.)
1692
Georg Brandlf725b952008-01-05 19:44:22 +00001693 If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new
Georg Brandl8ec7f652007-08-15 14:28:01 +00001694 process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
1695 exits normally, or ``-signal``, where *signal* is the signal that killed the
Georg Brandlf725b952008-01-05 19:44:22 +00001696 process. On Windows, the process id will actually be the process handle, so can
Georg Brandl8ec7f652007-08-15 14:28:01 +00001697 be used with the :func:`waitpid` function.
1698
Georg Brandlf725b952008-01-05 19:44:22 +00001699 The "l" and "v" variants of the :func:`spawn\*` functions differ in how
1700 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl8ec7f652007-08-15 14:28:01 +00001701 to work with if the number of parameters is fixed when the code is written; the
1702 individual parameters simply become additional parameters to the
Georg Brandlf725b952008-01-05 19:44:22 +00001703 :func:`spawnl\*` functions. The "v" variants are good when the number of
Georg Brandl8ec7f652007-08-15 14:28:01 +00001704 parameters is variable, with the arguments being passed in a list or tuple as
1705 the *args* parameter. In either case, the arguments to the child process must
1706 start with the name of the command being run.
1707
Georg Brandlf725b952008-01-05 19:44:22 +00001708 The variants which include a second "p" near the end (:func:`spawnlp`,
Georg Brandl8ec7f652007-08-15 14:28:01 +00001709 :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
1710 :envvar:`PATH` environment variable to locate the program *file*. When the
1711 environment is being replaced (using one of the :func:`spawn\*e` variants,
1712 discussed in the next paragraph), the new environment is used as the source of
1713 the :envvar:`PATH` variable. The other variants, :func:`spawnl`,
1714 :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
1715 :envvar:`PATH` variable to locate the executable; *path* must contain an
1716 appropriate absolute or relative path.
1717
1718 For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
Georg Brandlf725b952008-01-05 19:44:22 +00001719 (note that these all end in "e"), the *env* parameter must be a mapping
Georg Brandl8ec7f652007-08-15 14:28:01 +00001720 which is used to define the environment variables for the new process; the
1721 :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
1722 the new process to inherit the environment of the current process.
1723
1724 As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are
1725 equivalent::
1726
1727 import os
1728 os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
1729
1730 L = ['cp', 'index.html', '/dev/null']
1731 os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
1732
1733 Availability: Unix, Windows. :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
1734 and :func:`spawnvpe` are not available on Windows.
1735
1736 .. versionadded:: 1.6
1737
1738
1739.. data:: P_NOWAIT
1740 P_NOWAITO
1741
1742 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1743 functions. If either of these values is given, the :func:`spawn\*` functions
Georg Brandlf725b952008-01-05 19:44:22 +00001744 will return as soon as the new process has been created, with the process id as
Georg Brandl8ec7f652007-08-15 14:28:01 +00001745 the return value. Availability: Macintosh, Unix, Windows.
1746
1747 .. versionadded:: 1.6
1748
1749
1750.. data:: P_WAIT
1751
1752 Possible value for the *mode* parameter to the :func:`spawn\*` family of
1753 functions. If this is given as *mode*, the :func:`spawn\*` functions will not
1754 return until the new process has run to completion and will return the exit code
1755 of the process the run is successful, or ``-signal`` if a signal kills the
1756 process. Availability: Macintosh, Unix, Windows.
1757
1758 .. versionadded:: 1.6
1759
1760
1761.. data:: P_DETACH
1762 P_OVERLAY
1763
1764 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1765 functions. These are less portable than those listed above. :const:`P_DETACH`
1766 is similar to :const:`P_NOWAIT`, but the new process is detached from the
1767 console of the calling process. If :const:`P_OVERLAY` is used, the current
1768 process will be replaced; the :func:`spawn\*` function will not return.
1769 Availability: Windows.
1770
1771 .. versionadded:: 1.6
1772
1773
1774.. function:: startfile(path[, operation])
1775
1776 Start a file with its associated application.
1777
1778 When *operation* is not specified or ``'open'``, this acts like double-clicking
1779 the file in Windows Explorer, or giving the file name as an argument to the
1780 :program:`start` command from the interactive command shell: the file is opened
1781 with whatever application (if any) its extension is associated.
1782
1783 When another *operation* is given, it must be a "command verb" that specifies
1784 what should be done with the file. Common verbs documented by Microsoft are
1785 ``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` and
1786 ``'find'`` (to be used on directories).
1787
1788 :func:`startfile` returns as soon as the associated application is launched.
1789 There is no option to wait for the application to close, and no way to retrieve
1790 the application's exit status. The *path* parameter is relative to the current
1791 directory. If you want to use an absolute path, make sure the first character
1792 is not a slash (``'/'``); the underlying Win32 :cfunc:`ShellExecute` function
1793 doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that
1794 the path is properly encoded for Win32. Availability: Windows.
1795
1796 .. versionadded:: 2.0
1797
1798 .. versionadded:: 2.5
1799 The *operation* parameter.
1800
1801
1802.. function:: system(command)
1803
1804 Execute the command (a string) in a subshell. This is implemented by calling
1805 the Standard C function :cfunc:`system`, and has the same limitations. Changes
Georg Brandlf725b952008-01-05 19:44:22 +00001806 to :data:`os.environ`, :data:`sys.stdin`, etc. are not reflected in the
1807 environment of the executed command.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001808
1809 On Unix, the return value is the exit status of the process encoded in the
1810 format specified for :func:`wait`. Note that POSIX does not specify the meaning
1811 of the return value of the C :cfunc:`system` function, so the return value of
1812 the Python function is system-dependent.
1813
1814 On Windows, the return value is that returned by the system shell after running
1815 *command*, given by the Windows environment variable :envvar:`COMSPEC`: on
1816 :program:`command.com` systems (Windows 95, 98 and ME) this is always ``0``; on
1817 :program:`cmd.exe` systems (Windows NT, 2000 and XP) this is the exit status of
1818 the command run; on systems using a non-native shell, consult your shell
1819 documentation.
1820
1821 Availability: Macintosh, Unix, Windows.
1822
1823 The :mod:`subprocess` module provides more powerful facilities for spawning new
1824 processes and retrieving their results; using that module is preferable to using
1825 this function.
1826
1827
1828.. function:: times()
1829
1830 Return a 5-tuple of floating point numbers indicating accumulated (processor or
1831 other) times, in seconds. The items are: user time, system time, children's
1832 user time, children's system time, and elapsed real time since a fixed point in
1833 the past, in that order. See the Unix manual page :manpage:`times(2)` or the
1834 corresponding Windows Platform API documentation. Availability: Macintosh, Unix,
1835 Windows.
1836
1837
1838.. function:: wait()
1839
1840 Wait for completion of a child process, and return a tuple containing its pid
1841 and exit status indication: a 16-bit number, whose low byte is the signal number
1842 that killed the process, and whose high byte is the exit status (if the signal
1843 number is zero); the high bit of the low byte is set if a core file was
1844 produced. Availability: Macintosh, Unix.
1845
1846
1847.. function:: waitpid(pid, options)
1848
1849 The details of this function differ on Unix and Windows.
1850
1851 On Unix: Wait for completion of a child process given by process id *pid*, and
1852 return a tuple containing its process id and exit status indication (encoded as
1853 for :func:`wait`). The semantics of the call are affected by the value of the
1854 integer *options*, which should be ``0`` for normal operation.
1855
1856 If *pid* is greater than ``0``, :func:`waitpid` requests status information for
1857 that specific process. If *pid* is ``0``, the request is for the status of any
1858 child in the process group of the current process. If *pid* is ``-1``, the
1859 request pertains to any child of the current process. If *pid* is less than
1860 ``-1``, status is requested for any process in the process group ``-pid`` (the
1861 absolute value of *pid*).
1862
1863 On Windows: Wait for completion of a process given by process handle *pid*, and
1864 return a tuple containing *pid*, and its exit status shifted left by 8 bits
1865 (shifting makes cross-platform use of the function easier). A *pid* less than or
1866 equal to ``0`` has no special meaning on Windows, and raises an exception. The
1867 value of integer *options* has no effect. *pid* can refer to any process whose
1868 id is known, not necessarily a child process. The :func:`spawn` functions called
1869 with :const:`P_NOWAIT` return suitable process handles.
1870
1871
1872.. function:: wait3([options])
1873
1874 Similar to :func:`waitpid`, except no process id argument is given and a
1875 3-element tuple containing the child's process id, exit status indication, and
1876 resource usage information is returned. Refer to :mod:`resource`.\
1877 :func:`getrusage` for details on resource usage information. The option
1878 argument is the same as that provided to :func:`waitpid` and :func:`wait4`.
1879 Availability: Unix.
1880
1881 .. versionadded:: 2.5
1882
1883
1884.. function:: wait4(pid, options)
1885
1886 Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
1887 process id, exit status indication, and resource usage information is returned.
1888 Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage
1889 information. The arguments to :func:`wait4` are the same as those provided to
1890 :func:`waitpid`. Availability: Unix.
1891
1892 .. versionadded:: 2.5
1893
1894
1895.. data:: WNOHANG
1896
1897 The option for :func:`waitpid` to return immediately if no child process status
1898 is available immediately. The function returns ``(0, 0)`` in this case.
1899 Availability: Macintosh, Unix.
1900
1901
1902.. data:: WCONTINUED
1903
1904 This option causes child processes to be reported if they have been continued
1905 from a job control stop since their status was last reported. Availability: Some
1906 Unix systems.
1907
1908 .. versionadded:: 2.3
1909
1910
1911.. data:: WUNTRACED
1912
1913 This option causes child processes to be reported if they have been stopped but
1914 their current state has not been reported since they were stopped. Availability:
1915 Macintosh, Unix.
1916
1917 .. versionadded:: 2.3
1918
1919The following functions take a process status code as returned by
1920:func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be
1921used to determine the disposition of a process.
1922
1923
1924.. function:: WCOREDUMP(status)
1925
Georg Brandlf725b952008-01-05 19:44:22 +00001926 Return ``True`` if a core dump was generated for the process, otherwise
1927 return ``False``. Availability: Macintosh, Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001928
1929 .. versionadded:: 2.3
1930
1931
1932.. function:: WIFCONTINUED(status)
1933
Georg Brandlf725b952008-01-05 19:44:22 +00001934 Return ``True`` if the process has been continued from a job control stop,
1935 otherwise return ``False``. Availability: Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001936
1937 .. versionadded:: 2.3
1938
1939
1940.. function:: WIFSTOPPED(status)
1941
Georg Brandlf725b952008-01-05 19:44:22 +00001942 Return ``True`` if the process has been stopped, otherwise return
Georg Brandl8ec7f652007-08-15 14:28:01 +00001943 ``False``. Availability: Unix.
1944
1945
1946.. function:: WIFSIGNALED(status)
1947
Georg Brandlf725b952008-01-05 19:44:22 +00001948 Return ``True`` if the process exited due to a signal, otherwise return
Georg Brandl8ec7f652007-08-15 14:28:01 +00001949 ``False``. Availability: Macintosh, Unix.
1950
1951
1952.. function:: WIFEXITED(status)
1953
Georg Brandlf725b952008-01-05 19:44:22 +00001954 Return ``True`` if the process exited using the :manpage:`exit(2)` system call,
1955 otherwise return ``False``. Availability: Macintosh, Unix.
Georg Brandl8ec7f652007-08-15 14:28:01 +00001956
1957
1958.. function:: WEXITSTATUS(status)
1959
1960 If ``WIFEXITED(status)`` is true, return the integer parameter to the
1961 :manpage:`exit(2)` system call. Otherwise, the return value is meaningless.
1962 Availability: Macintosh, Unix.
1963
1964
1965.. function:: WSTOPSIG(status)
1966
1967 Return the signal which caused the process to stop. Availability: Macintosh,
1968 Unix.
1969
1970
1971.. function:: WTERMSIG(status)
1972
1973 Return the signal which caused the process to exit. Availability: Macintosh,
1974 Unix.
1975
1976
1977.. _os-path:
1978
1979Miscellaneous System Information
1980--------------------------------
1981
1982
1983.. function:: confstr(name)
1984
1985 Return string-valued system configuration values. *name* specifies the
1986 configuration value to retrieve; it may be a string which is the name of a
1987 defined system value; these names are specified in a number of standards (POSIX,
1988 Unix 95, Unix 98, and others). Some platforms define additional names as well.
1989 The names known to the host operating system are given as the keys of the
1990 ``confstr_names`` dictionary. For configuration variables not included in that
1991 mapping, passing an integer for *name* is also accepted. Availability:
1992 Macintosh, Unix.
1993
1994 If the configuration value specified by *name* isn't defined, ``None`` is
1995 returned.
1996
1997 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
1998 specific value for *name* is not supported by the host system, even if it is
1999 included in ``confstr_names``, an :exc:`OSError` is raised with
2000 :const:`errno.EINVAL` for the error number.
2001
2002
2003.. data:: confstr_names
2004
2005 Dictionary mapping names accepted by :func:`confstr` to the integer values
2006 defined for those names by the host operating system. This can be used to
2007 determine the set of names known to the system. Availability: Macintosh, Unix.
2008
2009
2010.. function:: getloadavg()
2011
Georg Brandl57fe0f22008-01-12 10:53:29 +00002012 Return the number of processes in the system run queue averaged over the last
2013 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was
Georg Brandl8ec7f652007-08-15 14:28:01 +00002014 unobtainable.
2015
2016 .. versionadded:: 2.3
2017
2018
2019.. function:: sysconf(name)
2020
2021 Return integer-valued system configuration values. If the configuration value
2022 specified by *name* isn't defined, ``-1`` is returned. The comments regarding
2023 the *name* parameter for :func:`confstr` apply here as well; the dictionary that
2024 provides information on the known names is given by ``sysconf_names``.
2025 Availability: Macintosh, Unix.
2026
2027
2028.. data:: sysconf_names
2029
2030 Dictionary mapping names accepted by :func:`sysconf` to the integer values
2031 defined for those names by the host operating system. This can be used to
2032 determine the set of names known to the system. Availability: Macintosh, Unix.
2033
Georg Brandlf725b952008-01-05 19:44:22 +00002034The following data values are used to support path manipulation operations. These
Georg Brandl8ec7f652007-08-15 14:28:01 +00002035are defined for all platforms.
2036
2037Higher-level operations on pathnames are defined in the :mod:`os.path` module.
2038
2039
2040.. data:: curdir
2041
2042 The constant string used by the operating system to refer to the current
2043 directory. For example: ``'.'`` for POSIX or ``':'`` for Mac OS 9. Also
2044 available via :mod:`os.path`.
2045
2046
2047.. data:: pardir
2048
2049 The constant string used by the operating system to refer to the parent
2050 directory. For example: ``'..'`` for POSIX or ``'::'`` for Mac OS 9. Also
2051 available via :mod:`os.path`.
2052
2053
2054.. data:: sep
2055
2056 The character used by the operating system to separate pathname components, for
2057 example, ``'/'`` for POSIX or ``':'`` for Mac OS 9. Note that knowing this is
2058 not sufficient to be able to parse or concatenate pathnames --- use
2059 :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
2060 useful. Also available via :mod:`os.path`.
2061
2062
2063.. data:: altsep
2064
2065 An alternative character used by the operating system to separate pathname
2066 components, or ``None`` if only one separator character exists. This is set to
2067 ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
2068 :mod:`os.path`.
2069
2070
2071.. data:: extsep
2072
2073 The character which separates the base filename from the extension; for example,
2074 the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.
2075
2076 .. versionadded:: 2.2
2077
2078
2079.. data:: pathsep
2080
2081 The character conventionally used by the operating system to separate search
2082 path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
2083 Windows. Also available via :mod:`os.path`.
2084
2085
2086.. data:: defpath
2087
2088 The default search path used by :func:`exec\*p\*` and :func:`spawn\*p\*` if the
2089 environment doesn't have a ``'PATH'`` key. Also available via :mod:`os.path`.
2090
2091
2092.. data:: linesep
2093
2094 The string used to separate (or, rather, terminate) lines on the current
2095 platform. This may be a single character, such as ``'\n'`` for POSIX or
2096 ``'\r'`` for Mac OS, or multiple characters, for example, ``'\r\n'`` for
2097 Windows. Do not use *os.linesep* as a line terminator when writing files opened
2098 in text mode (the default); use a single ``'\n'`` instead, on all platforms.
2099
2100
2101.. data:: devnull
2102
2103 The file path of the null device. For example: ``'/dev/null'`` for POSIX or
2104 ``'Dev:Nul'`` for Mac OS 9. Also available via :mod:`os.path`.
2105
2106 .. versionadded:: 2.4
2107
2108
2109.. _os-miscfunc:
2110
2111Miscellaneous Functions
2112-----------------------
2113
2114
2115.. function:: urandom(n)
2116
2117 Return a string of *n* random bytes suitable for cryptographic use.
2118
2119 This function returns random bytes from an OS-specific randomness source. The
2120 returned data should be unpredictable enough for cryptographic applications,
2121 though its exact quality depends on the OS implementation. On a UNIX-like
2122 system this will query /dev/urandom, and on Windows it will use CryptGenRandom.
2123 If a randomness source is not found, :exc:`NotImplementedError` will be raised.
2124
2125 .. versionadded:: 2.4
2126