blob: fc62b0b31d3380bc89727067fc20a5fcd840e973 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`os` --- Miscellaneous operating system interfaces
2=======================================================
3
4.. module:: os
5 :synopsis: Miscellaneous operating system interfaces.
6
7
Christian Heimesa62da1d2008-01-12 19:39:10 +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 Brandl116aa622007-08-15 14:28:22 +000015
Christian Heimesa62da1d2008-01-12 19:39:10 +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 Brandl116aa622007-08-15 14:28:22 +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
Christian Heimesa62da1d2008-01-12 19:39:10 +000025.. note::
Georg Brandl116aa622007-08-15 14:28:22 +000026
Georg Brandl76e55382008-10-08 16:34:57 +000027 All functions accepting path or file names accept both bytes and string
28 objects, and result in an object of the same type, if a path or file name is
29 returned.
30
31.. note::
32
Georg Brandlc575c902008-09-13 17:46:05 +000033 If not separately noted, all functions that claim "Availability: Unix" are
34 supported on Mac OS X, which builds on a Unix core.
35
36.. note::
37
Christian Heimesa62da1d2008-01-12 19:39:10 +000038 All functions in this module raise :exc:`OSError` in the case of invalid or
39 inaccessible file names and paths, or other arguments that have the correct
40 type, but are not accepted by the operating system.
Georg Brandl116aa622007-08-15 14:28:22 +000041
Georg Brandl116aa622007-08-15 14:28:22 +000042.. exception:: error
43
Christian Heimesa62da1d2008-01-12 19:39:10 +000044 An alias for the built-in :exc:`OSError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +000045
46
47.. data:: name
48
49 The name of the operating system dependent module imported. The following names
50 have currently been registered: ``'posix'``, ``'nt'``, ``'mac'``, ``'os2'``,
Skip Montanaro7a98be22007-08-16 14:35:24 +000051 ``'ce'``, ``'java'``.
Georg Brandl116aa622007-08-15 14:28:22 +000052
53
54.. data:: path
55
56 The corresponding operating system dependent standard module for pathname
Georg Brandlc575c902008-09-13 17:46:05 +000057 operations, such as :mod:`posixpath` or :mod:`ntpath`. Thus, given the proper
Georg Brandl116aa622007-08-15 14:28:22 +000058 imports, ``os.path.split(file)`` is equivalent to but more portable than
59 ``posixpath.split(file)``. Note that this is also an importable module: it may
60 be imported directly as :mod:`os.path`.
61
62
63.. _os-procinfo:
64
65Process Parameters
66------------------
67
68These functions and data items provide information and operate on the current
69process and user.
70
71
72.. data:: environ
73
74 A mapping object representing the string environment. For example,
75 ``environ['HOME']`` is the pathname of your home directory (on some platforms),
76 and is equivalent to ``getenv("HOME")`` in C.
77
78 This mapping is captured the first time the :mod:`os` module is imported,
79 typically during Python startup as part of processing :file:`site.py`. Changes
80 to the environment made after this time are not reflected in ``os.environ``,
81 except for changes made by modifying ``os.environ`` directly.
82
83 If the platform supports the :func:`putenv` function, this mapping may be used
84 to modify the environment as well as query the environment. :func:`putenv` will
85 be called automatically when the mapping is modified.
86
87 .. note::
88
89 Calling :func:`putenv` directly does not change ``os.environ``, so it's better
90 to modify ``os.environ``.
91
92 .. note::
93
Georg Brandlc575c902008-09-13 17:46:05 +000094 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
95 cause memory leaks. Refer to the system documentation for
96 :cfunc:`putenv`.
Georg Brandl116aa622007-08-15 14:28:22 +000097
98 If :func:`putenv` is not provided, a modified copy of this mapping may be
99 passed to the appropriate process-creation functions to cause child processes
100 to use a modified environment.
101
Georg Brandl9afde1c2007-11-01 20:32:30 +0000102 If the platform supports the :func:`unsetenv` function, you can delete items in
Georg Brandl116aa622007-08-15 14:28:22 +0000103 this mapping to unset environment variables. :func:`unsetenv` will be called
Georg Brandl9afde1c2007-11-01 20:32:30 +0000104 automatically when an item is deleted from ``os.environ``, and when
105 one of the :meth:`pop` or :meth:`clear` methods is called.
106
Georg Brandl116aa622007-08-15 14:28:22 +0000107
108.. function:: chdir(path)
109 fchdir(fd)
110 getcwd()
111 :noindex:
112
113 These functions are described in :ref:`os-file-dir`.
114
115
116.. function:: ctermid()
117
118 Return the filename corresponding to the controlling terminal of the process.
119 Availability: Unix.
120
121
122.. function:: getegid()
123
124 Return the effective group id of the current process. This corresponds to the
Christian Heimesfaf2f632008-01-06 16:59:19 +0000125 "set id" bit on the file being executed in the current process. Availability:
Georg Brandl116aa622007-08-15 14:28:22 +0000126 Unix.
127
128
129.. function:: geteuid()
130
131 .. index:: single: user; effective id
132
Christian Heimesfaf2f632008-01-06 16:59:19 +0000133 Return the current process's effective user id. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000134
135
136.. function:: getgid()
137
138 .. index:: single: process; group
139
140 Return the real group id of the current process. Availability: Unix.
141
142
143.. function:: getgroups()
144
145 Return list of supplemental group ids associated with the current process.
146 Availability: Unix.
147
148
149.. function:: getlogin()
150
151 Return the name of the user logged in on the controlling terminal of the
152 process. For most purposes, it is more useful to use the environment variable
153 :envvar:`LOGNAME` to find out who the user is, or
154 ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the currently
Christian Heimesfaf2f632008-01-06 16:59:19 +0000155 effective user id. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000156
157
158.. function:: getpgid(pid)
159
160 Return the process group id of the process with process id *pid*. If *pid* is 0,
161 the process group id of the current process is returned. Availability: Unix.
162
Georg Brandl116aa622007-08-15 14:28:22 +0000163
164.. function:: getpgrp()
165
166 .. index:: single: process; group
167
168 Return the id of the current process group. Availability: Unix.
169
170
171.. function:: getpid()
172
173 .. index:: single: process; id
174
175 Return the current process id. Availability: Unix, Windows.
176
177
178.. function:: getppid()
179
180 .. index:: single: process; id of parent
181
182 Return the parent's process id. Availability: Unix.
183
184
185.. function:: getuid()
186
187 .. index:: single: user; id
188
Christian Heimesfaf2f632008-01-06 16:59:19 +0000189 Return the current process's user id. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000190
191
192.. function:: getenv(varname[, value])
193
194 Return the value of the environment variable *varname* if it exists, or *value*
195 if it doesn't. *value* defaults to ``None``. Availability: most flavors of
196 Unix, Windows.
197
198
199.. function:: putenv(varname, value)
200
201 .. index:: single: environment variables; setting
202
203 Set the environment variable named *varname* to the string *value*. Such
204 changes to the environment affect subprocesses started with :func:`os.system`,
205 :func:`popen` or :func:`fork` and :func:`execv`. Availability: most flavors of
206 Unix, Windows.
207
208 .. note::
209
Georg Brandlc575c902008-09-13 17:46:05 +0000210 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
211 cause memory leaks. Refer to the system documentation for putenv.
Georg Brandl116aa622007-08-15 14:28:22 +0000212
213 When :func:`putenv` is supported, assignments to items in ``os.environ`` are
214 automatically translated into corresponding calls to :func:`putenv`; however,
215 calls to :func:`putenv` don't update ``os.environ``, so it is actually
216 preferable to assign to items of ``os.environ``.
217
218
219.. function:: setegid(egid)
220
221 Set the current process's effective group id. Availability: Unix.
222
223
224.. function:: seteuid(euid)
225
226 Set the current process's effective user id. Availability: Unix.
227
228
229.. function:: setgid(gid)
230
231 Set the current process' group id. Availability: Unix.
232
233
234.. function:: setgroups(groups)
235
236 Set the list of supplemental group ids associated with the current process to
237 *groups*. *groups* must be a sequence, and each element must be an integer
Christian Heimesfaf2f632008-01-06 16:59:19 +0000238 identifying a group. This operation is typically available only to the superuser.
Georg Brandl116aa622007-08-15 14:28:22 +0000239 Availability: Unix.
240
Georg Brandl116aa622007-08-15 14:28:22 +0000241
242.. function:: setpgrp()
243
Christian Heimesfaf2f632008-01-06 16:59:19 +0000244 Call the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on
Georg Brandl116aa622007-08-15 14:28:22 +0000245 which version is implemented (if any). See the Unix manual for the semantics.
246 Availability: Unix.
247
248
249.. function:: setpgid(pid, pgrp)
250
Christian Heimesfaf2f632008-01-06 16:59:19 +0000251 Call the system call :cfunc:`setpgid` to set the process group id of the
Georg Brandl116aa622007-08-15 14:28:22 +0000252 process with id *pid* to the process group with id *pgrp*. See the Unix manual
253 for the semantics. Availability: Unix.
254
255
256.. function:: setreuid(ruid, euid)
257
258 Set the current process's real and effective user ids. Availability: Unix.
259
260
261.. function:: setregid(rgid, egid)
262
263 Set the current process's real and effective group ids. Availability: Unix.
264
265
266.. function:: getsid(pid)
267
Christian Heimesfaf2f632008-01-06 16:59:19 +0000268 Call the system call :cfunc:`getsid`. See the Unix manual for the semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000269 Availability: Unix.
270
Georg Brandl116aa622007-08-15 14:28:22 +0000271
272.. function:: setsid()
273
Christian Heimesfaf2f632008-01-06 16:59:19 +0000274 Call the system call :cfunc:`setsid`. See the Unix manual for the semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000275 Availability: Unix.
276
277
278.. function:: setuid(uid)
279
280 .. index:: single: user; id, setting
281
Christian Heimesfaf2f632008-01-06 16:59:19 +0000282 Set the current process's user id. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000283
Georg Brandl116aa622007-08-15 14:28:22 +0000284
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000285.. placed in this section since it relates to errno.... a little weak
Georg Brandl116aa622007-08-15 14:28:22 +0000286.. function:: strerror(code)
287
288 Return the error message corresponding to the error code in *code*.
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000289 On platforms where :cfunc:`strerror` returns ``NULL`` when given an unknown
290 error number, :exc:`ValueError` is raised. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000291
292
293.. function:: umask(mask)
294
Christian Heimesfaf2f632008-01-06 16:59:19 +0000295 Set the current numeric umask and return the previous umask. Availability:
Georg Brandl116aa622007-08-15 14:28:22 +0000296 Unix, Windows.
297
298
299.. function:: uname()
300
301 .. index::
302 single: gethostname() (in module socket)
303 single: gethostbyaddr() (in module socket)
304
305 Return a 5-tuple containing information identifying the current operating
306 system. The tuple contains 5 strings: ``(sysname, nodename, release, version,
307 machine)``. Some systems truncate the nodename to 8 characters or to the
308 leading component; a better way to get the hostname is
309 :func:`socket.gethostname` or even
310 ``socket.gethostbyaddr(socket.gethostname())``. Availability: recent flavors of
311 Unix.
312
313
314.. function:: unsetenv(varname)
315
316 .. index:: single: environment variables; deleting
317
318 Unset (delete) the environment variable named *varname*. Such changes to the
319 environment affect subprocesses started with :func:`os.system`, :func:`popen` or
320 :func:`fork` and :func:`execv`. Availability: most flavors of Unix, Windows.
321
322 When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is
323 automatically translated into a corresponding call to :func:`unsetenv`; however,
324 calls to :func:`unsetenv` don't update ``os.environ``, so it is actually
325 preferable to delete items of ``os.environ``.
326
327
328.. _os-newstreams:
329
330File Object Creation
331--------------------
332
333These functions create new file objects. (See also :func:`open`.)
334
335
336.. function:: fdopen(fd[, mode[, bufsize]])
337
338 .. index:: single: I/O control; buffering
339
340 Return an open file object connected to the file descriptor *fd*. The *mode*
341 and *bufsize* arguments have the same meaning as the corresponding arguments to
Georg Brandlc575c902008-09-13 17:46:05 +0000342 the built-in :func:`open` function. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000343
Georg Brandl55ac8f02007-09-01 13:51:09 +0000344 When specified, the *mode* argument must start with one of the letters
345 ``'r'``, ``'w'``, or ``'a'``, otherwise a :exc:`ValueError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000346
Georg Brandl55ac8f02007-09-01 13:51:09 +0000347 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).
Georg Brandl116aa622007-08-15 14:28:22 +0000350
351
Georg Brandl116aa622007-08-15 14:28:22 +0000352.. _os-fd-ops:
353
354File Descriptor Operations
355--------------------------
356
357These functions operate on I/O streams referenced using file descriptors.
358
359File descriptors are small integers corresponding to a file that has been opened
360by the current process. For example, standard input is usually file descriptor
3610, standard output is 1, and standard error is 2. Further files opened by a
362process will then be assigned 3, 4, 5, and so forth. The name "file descriptor"
363is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
364by file descriptors.
365
366
367.. function:: close(fd)
368
Georg Brandlc575c902008-09-13 17:46:05 +0000369 Close file descriptor *fd*. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000370
371 .. note::
372
373 This function is intended for low-level I/O and must be applied to a file
374 descriptor as returned by :func:`open` or :func:`pipe`. To close a "file
375 object" returned by the built-in function :func:`open` or by :func:`popen` or
376 :func:`fdopen`, use its :meth:`close` method.
377
378
Christian Heimesfdab48e2008-01-20 09:06:41 +0000379.. function:: closerange(fd_low, fd_high)
380
381 Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive),
Georg Brandlc575c902008-09-13 17:46:05 +0000382 ignoring errors. Availability: Unix, Windows. Equivalent to::
Christian Heimesfdab48e2008-01-20 09:06:41 +0000383
384 for fd in xrange(fd_low, fd_high):
385 try:
386 os.close(fd)
387 except OSError:
388 pass
389
Christian Heimesfdab48e2008-01-20 09:06:41 +0000390
Georg Brandl81f11302007-12-21 08:45:42 +0000391.. function:: device_encoding(fd)
392
393 Return a string describing the encoding of the device associated with *fd*
394 if it is connected to a terminal; else return :const:`None`.
395
396
Georg Brandl116aa622007-08-15 14:28:22 +0000397.. function:: dup(fd)
398
Georg Brandlc575c902008-09-13 17:46:05 +0000399 Return a duplicate of file descriptor *fd*. Availability: Unix,
Georg Brandl116aa622007-08-15 14:28:22 +0000400 Windows.
401
402
403.. function:: dup2(fd, fd2)
404
405 Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary.
Georg Brandlc575c902008-09-13 17:46:05 +0000406 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000407
408
Christian Heimes4e30a842007-11-30 22:12:06 +0000409.. function:: fchmod(fd, mode)
410
411 Change the mode of the file given by *fd* to the numeric *mode*. See the docs
412 for :func:`chmod` for possible values of *mode*. Availability: Unix.
413
414
415.. function:: fchown(fd, uid, gid)
416
417 Change the owner and group id of the file given by *fd* to the numeric *uid*
418 and *gid*. To leave one of the ids unchanged, set it to -1.
419 Availability: Unix.
420
421
Georg Brandl116aa622007-08-15 14:28:22 +0000422.. function:: fdatasync(fd)
423
424 Force write of file with filedescriptor *fd* to disk. Does not force update of
425 metadata. Availability: Unix.
426
427
428.. function:: fpathconf(fd, name)
429
430 Return system configuration information relevant to an open file. *name*
431 specifies the configuration value to retrieve; it may be a string which is the
432 name of a defined system value; these names are specified in a number of
433 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
434 additional names as well. The names known to the host operating system are
435 given in the ``pathconf_names`` dictionary. For configuration variables not
436 included in that mapping, passing an integer for *name* is also accepted.
Georg Brandlc575c902008-09-13 17:46:05 +0000437 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000438
439 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
440 specific value for *name* is not supported by the host system, even if it is
441 included in ``pathconf_names``, an :exc:`OSError` is raised with
442 :const:`errno.EINVAL` for the error number.
443
444
445.. function:: fstat(fd)
446
447 Return status for file descriptor *fd*, like :func:`stat`. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +0000448 Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000449
450
451.. function:: fstatvfs(fd)
452
453 Return information about the filesystem containing the file associated with file
454 descriptor *fd*, like :func:`statvfs`. Availability: Unix.
455
456
457.. function:: fsync(fd)
458
459 Force write of file with filedescriptor *fd* to disk. On Unix, this calls the
460 native :cfunc:`fsync` function; on Windows, the MS :cfunc:`_commit` function.
461
462 If you're starting with a Python file object *f*, first do ``f.flush()``, and
463 then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated
Georg Brandlc575c902008-09-13 17:46:05 +0000464 with *f* are written to disk. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000465
466
467.. function:: ftruncate(fd, length)
468
469 Truncate the file corresponding to file descriptor *fd*, so that it is at most
Georg Brandlc575c902008-09-13 17:46:05 +0000470 *length* bytes in size. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000471
472
473.. function:: isatty(fd)
474
475 Return ``True`` if the file descriptor *fd* is open and connected to a
Georg Brandlc575c902008-09-13 17:46:05 +0000476 tty(-like) device, else ``False``. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000477
478
479.. function:: lseek(fd, pos, how)
480
Christian Heimesfaf2f632008-01-06 16:59:19 +0000481 Set the current position of file descriptor *fd* to position *pos*, modified
482 by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the
483 beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the
484 current position; :const:`os.SEEK_END` or ``2`` to set it relative to the end of
Georg Brandlc575c902008-09-13 17:46:05 +0000485 the file. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000486
487
488.. function:: open(file, flags[, mode])
489
Georg Brandlf4a41232008-05-26 17:55:52 +0000490 Open the file *file* and set various flags according to *flags* and possibly
491 its mode according to *mode*. The default *mode* is ``0o777`` (octal), and
492 the current umask value is first masked out. Return the file descriptor for
Georg Brandlc575c902008-09-13 17:46:05 +0000493 the newly opened file. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000494
495 For a description of the flag and mode values, see the C run-time documentation;
496 flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
497 this module too (see below).
498
499 .. note::
500
501 This function is intended for low-level I/O. For normal usage, use the built-in
502 function :func:`open`, which returns a "file object" with :meth:`read` and
503 :meth:`write` methods (and many more). To wrap a file descriptor in a "file
504 object", use :func:`fdopen`.
505
506
507.. function:: openpty()
508
509 .. index:: module: pty
510
511 Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master,
512 slave)`` for the pty and the tty, respectively. For a (slightly) more portable
Georg Brandlc575c902008-09-13 17:46:05 +0000513 approach, use the :mod:`pty` module. Availability: some flavors of
Georg Brandl116aa622007-08-15 14:28:22 +0000514 Unix.
515
516
517.. function:: pipe()
518
519 Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading
Georg Brandlc575c902008-09-13 17:46:05 +0000520 and writing, respectively. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000521
522
523.. function:: read(fd, n)
524
525 Read at most *n* bytes from file descriptor *fd*. Return a string containing the
526 bytes read. If the end of the file referred to by *fd* has been reached, an
Georg Brandlc575c902008-09-13 17:46:05 +0000527 empty string is returned. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000528
529 .. note::
530
531 This function is intended for low-level I/O and must be applied to a file
532 descriptor as returned by :func:`open` or :func:`pipe`. To read a "file object"
533 returned by the built-in function :func:`open` or by :func:`popen` or
Christian Heimesfaf2f632008-01-06 16:59:19 +0000534 :func:`fdopen`, or :data:`sys.stdin`, use its :meth:`read` or :meth:`readline`
Georg Brandl116aa622007-08-15 14:28:22 +0000535 methods.
536
537
538.. function:: tcgetpgrp(fd)
539
540 Return the process group associated with the terminal given by *fd* (an open
Georg Brandlc575c902008-09-13 17:46:05 +0000541 file descriptor as returned by :func:`open`). Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000542
543
544.. function:: tcsetpgrp(fd, pg)
545
546 Set the process group associated with the terminal given by *fd* (an open file
Georg Brandlc575c902008-09-13 17:46:05 +0000547 descriptor as returned by :func:`open`) to *pg*. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000548
549
550.. function:: ttyname(fd)
551
552 Return a string which specifies the terminal device associated with
Georg Brandl9afde1c2007-11-01 20:32:30 +0000553 file descriptor *fd*. If *fd* is not associated with a terminal device, an
Georg Brandlc575c902008-09-13 17:46:05 +0000554 exception is raised. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000555
556
557.. function:: write(fd, str)
558
559 Write the string *str* to file descriptor *fd*. Return the number of bytes
Georg Brandlc575c902008-09-13 17:46:05 +0000560 actually written. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000561
562 .. note::
563
564 This function is intended for low-level I/O and must be applied to a file
565 descriptor as returned by :func:`open` or :func:`pipe`. To write a "file
566 object" returned by the built-in function :func:`open` or by :func:`popen` or
Christian Heimesfaf2f632008-01-06 16:59:19 +0000567 :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its :meth:`write`
Georg Brandl116aa622007-08-15 14:28:22 +0000568 method.
569
Georg Brandlaf265f42008-12-07 15:06:20 +0000570The following constants are options for the *flags* parameter to the
571:func:`open` function. They can be combined using the bitwise OR operator
572``|``. Some of them are not available on all platforms. For descriptions of
573their availability and use, consult the :manpage:`open(2)` manual page on Unix
574or `the MSDN <http://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>` on Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000575
576
577.. data:: O_RDONLY
578 O_WRONLY
579 O_RDWR
580 O_APPEND
581 O_CREAT
582 O_EXCL
583 O_TRUNC
584
Georg Brandlaf265f42008-12-07 15:06:20 +0000585 These constants are available on Unix and Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000586
587
588.. data:: O_DSYNC
589 O_RSYNC
590 O_SYNC
591 O_NDELAY
592 O_NONBLOCK
593 O_NOCTTY
594 O_SHLOCK
595 O_EXLOCK
596
Georg Brandlaf265f42008-12-07 15:06:20 +0000597 These constants are only available on Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000598
599
600.. data:: O_BINARY
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000601 O_NOINHERIT
Georg Brandl116aa622007-08-15 14:28:22 +0000602 O_SHORT_LIVED
603 O_TEMPORARY
604 O_RANDOM
605 O_SEQUENTIAL
606 O_TEXT
607
Georg Brandlaf265f42008-12-07 15:06:20 +0000608 These constants are only available on Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000609
610
Alexandre Vassalottibee32532008-05-16 18:15:12 +0000611.. data:: O_ASYNC
612 O_DIRECT
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000613 O_DIRECTORY
614 O_NOFOLLOW
615 O_NOATIME
616
Georg Brandlaf265f42008-12-07 15:06:20 +0000617 These constants are GNU extensions and not present if they are not defined by
618 the C library.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000619
620
Georg Brandl116aa622007-08-15 14:28:22 +0000621.. data:: SEEK_SET
622 SEEK_CUR
623 SEEK_END
624
625 Parameters to the :func:`lseek` function. Their values are 0, 1, and 2,
Georg Brandlc575c902008-09-13 17:46:05 +0000626 respectively. Availability: Windows, Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000627
Georg Brandl116aa622007-08-15 14:28:22 +0000628
629.. _os-file-dir:
630
631Files and Directories
632---------------------
633
Georg Brandl116aa622007-08-15 14:28:22 +0000634.. function:: access(path, mode)
635
636 Use the real uid/gid to test for access to *path*. Note that most operations
637 will use the effective uid/gid, therefore this routine can be used in a
638 suid/sgid environment to test if the invoking user has the specified access to
639 *path*. *mode* should be :const:`F_OK` to test the existence of *path*, or it
640 can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and
641 :const:`X_OK` to test permissions. Return :const:`True` if access is allowed,
642 :const:`False` if not. See the Unix man page :manpage:`access(2)` for more
Georg Brandlc575c902008-09-13 17:46:05 +0000643 information. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000644
645 .. note::
646
647 Using :func:`access` to check if a user is authorized to e.g. open a file before
648 actually doing so using :func:`open` creates a security hole, because the user
649 might exploit the short time interval between checking and opening the file to
650 manipulate it.
651
652 .. note::
653
654 I/O operations may fail even when :func:`access` indicates that they would
655 succeed, particularly for operations on network filesystems which may have
656 permissions semantics beyond the usual POSIX permission-bit model.
657
658
659.. data:: F_OK
660
661 Value to pass as the *mode* parameter of :func:`access` to test the existence of
662 *path*.
663
664
665.. data:: R_OK
666
667 Value to include in the *mode* parameter of :func:`access` to test the
668 readability of *path*.
669
670
671.. data:: W_OK
672
673 Value to include in the *mode* parameter of :func:`access` to test the
674 writability of *path*.
675
676
677.. data:: X_OK
678
679 Value to include in the *mode* parameter of :func:`access` to determine if
680 *path* can be executed.
681
682
683.. function:: chdir(path)
684
685 .. index:: single: directory; changing
686
Georg Brandlc575c902008-09-13 17:46:05 +0000687 Change the current working directory to *path*. Availability: Unix,
Georg Brandl116aa622007-08-15 14:28:22 +0000688 Windows.
689
690
691.. function:: fchdir(fd)
692
693 Change the current working directory to the directory represented by the file
694 descriptor *fd*. The descriptor must refer to an opened directory, not an open
695 file. Availability: Unix.
696
Georg Brandl116aa622007-08-15 14:28:22 +0000697
698.. function:: getcwd()
699
Georg Brandl76e55382008-10-08 16:34:57 +0000700 Return a string representing the current working directory. On Unix
701 platforms, this function may raise :exc:`UnicodeDecodeError` if the name of
702 the current directory is not decodable in the file system encoding. Use
703 :func:`getcwdb` if you need the call to never fail. Availability: Unix,
704 Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000705
706
Martin v. Löwisa731b992008-10-07 06:36:31 +0000707.. function:: getcwdb()
Georg Brandl116aa622007-08-15 14:28:22 +0000708
Georg Brandl76e55382008-10-08 16:34:57 +0000709 Return a bytestring representing the current working directory.
Georg Brandlc575c902008-09-13 17:46:05 +0000710 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000711
Georg Brandl116aa622007-08-15 14:28:22 +0000712
713.. function:: chflags(path, flags)
714
715 Set the flags of *path* to the numeric *flags*. *flags* may take a combination
716 (bitwise OR) of the following values (as defined in the :mod:`stat` module):
717
718 * ``UF_NODUMP``
719 * ``UF_IMMUTABLE``
720 * ``UF_APPEND``
721 * ``UF_OPAQUE``
722 * ``UF_NOUNLINK``
723 * ``SF_ARCHIVED``
724 * ``SF_IMMUTABLE``
725 * ``SF_APPEND``
726 * ``SF_NOUNLINK``
727 * ``SF_SNAPSHOT``
728
Georg Brandlc575c902008-09-13 17:46:05 +0000729 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000730
Georg Brandl116aa622007-08-15 14:28:22 +0000731
732.. function:: chroot(path)
733
734 Change the root directory of the current process to *path*. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +0000735 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000736
Georg Brandl116aa622007-08-15 14:28:22 +0000737
738.. function:: chmod(path, mode)
739
740 Change the mode of *path* to the numeric *mode*. *mode* may take one of the
Christian Heimesfaf2f632008-01-06 16:59:19 +0000741 following values (as defined in the :mod:`stat` module) or bitwise ORed
Georg Brandl116aa622007-08-15 14:28:22 +0000742 combinations of them:
743
744 * ``stat.S_ISUID``
745 * ``stat.S_ISGID``
746 * ``stat.S_ENFMT``
747 * ``stat.S_ISVTX``
748 * ``stat.S_IREAD``
749 * ``stat.S_IWRITE``
750 * ``stat.S_IEXEC``
751 * ``stat.S_IRWXU``
752 * ``stat.S_IRUSR``
753 * ``stat.S_IWUSR``
754 * ``stat.S_IXUSR``
755 * ``stat.S_IRWXG``
756 * ``stat.S_IRGRP``
757 * ``stat.S_IWGRP``
758 * ``stat.S_IXGRP``
759 * ``stat.S_IRWXO``
760 * ``stat.S_IROTH``
761 * ``stat.S_IWOTH``
762 * ``stat.S_IXOTH``
763
Georg Brandlc575c902008-09-13 17:46:05 +0000764 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000765
766 .. note::
767
768 Although Windows supports :func:`chmod`, you can only set the file's read-only
769 flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD``
770 constants or a corresponding integer value). All other bits are
771 ignored.
772
773
774.. function:: chown(path, uid, gid)
775
776 Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave
Georg Brandlc575c902008-09-13 17:46:05 +0000777 one of the ids unchanged, set it to -1. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000778
779
780.. function:: lchflags(path, flags)
781
782 Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not
783 follow symbolic links. Availability: Unix.
784
Georg Brandl116aa622007-08-15 14:28:22 +0000785
Christian Heimes93852662007-12-01 12:22:32 +0000786.. function:: lchmod(path, mode)
787
788 Change the mode of *path* to the numeric *mode*. If path is a symlink, this
789 affects the symlink rather than the target. See the docs for :func:`chmod`
790 for possible values of *mode*. Availability: Unix.
791
Christian Heimes93852662007-12-01 12:22:32 +0000792
Georg Brandl116aa622007-08-15 14:28:22 +0000793.. function:: lchown(path, uid, gid)
794
Christian Heimesfaf2f632008-01-06 16:59:19 +0000795 Change the owner and group id of *path* to the numeric *uid* and *gid*. This
Georg Brandlc575c902008-09-13 17:46:05 +0000796 function will not follow symbolic links. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000797
Georg Brandl116aa622007-08-15 14:28:22 +0000798
Benjamin Peterson5879d412009-03-30 14:51:56 +0000799.. function:: link(source, link_name)
Georg Brandl116aa622007-08-15 14:28:22 +0000800
Benjamin Peterson5879d412009-03-30 14:51:56 +0000801 Create a hard link pointing to *source* named *link_name*. Availability:
802 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000803
804
805.. function:: listdir(path)
806
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000807 Return a list containing the names of the entries in the directory given by
808 *path*. The list is in arbitrary order. It does not include the special
809 entries ``'.'`` and ``'..'`` even if they are present in the directory.
810 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000811
Georg Brandl76e55382008-10-08 16:34:57 +0000812 This function can be called with a bytes or string argument. In the bytes
813 case, all filenames will be listed as returned by the underlying API. In the
814 string case, filenames will be decoded using the file system encoding, and
815 skipped if a decoding error occurs.
Georg Brandl116aa622007-08-15 14:28:22 +0000816
817
818.. function:: lstat(path)
819
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000820 Like :func:`stat`, but do not follow symbolic links. This is an alias for
821 :func:`stat` on platforms that do not support symbolic links, such as
822 Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000823
824
825.. function:: mkfifo(path[, mode])
826
Georg Brandlf4a41232008-05-26 17:55:52 +0000827 Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The
828 default *mode* is ``0o666`` (octal). The current umask value is first masked
Georg Brandlc575c902008-09-13 17:46:05 +0000829 out from the mode. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000830
831 FIFOs are pipes that can be accessed like regular files. FIFOs exist until they
832 are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
833 rendezvous between "client" and "server" type processes: the server opens the
834 FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo`
835 doesn't open the FIFO --- it just creates the rendezvous point.
836
837
Georg Brandlf4a41232008-05-26 17:55:52 +0000838.. function:: mknod(filename[, mode=0o600, device])
Georg Brandl116aa622007-08-15 14:28:22 +0000839
840 Create a filesystem node (file, device special file or named pipe) named
841 *filename*. *mode* specifies both the permissions to use and the type of node to
842 be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
843 ``stat.S_IFCHR``, ``stat.S_IFBLK``,
844 and ``stat.S_IFIFO`` (those constants are available in :mod:`stat`).
845 For ``stat.S_IFCHR`` and
846 ``stat.S_IFBLK``, *device* defines the newly created device special file (probably using
847 :func:`os.makedev`), otherwise it is ignored.
848
Georg Brandl116aa622007-08-15 14:28:22 +0000849
850.. function:: major(device)
851
Christian Heimesfaf2f632008-01-06 16:59:19 +0000852 Extract the device major number from a raw device number (usually the
Georg Brandl116aa622007-08-15 14:28:22 +0000853 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
854
Georg Brandl116aa622007-08-15 14:28:22 +0000855
856.. function:: minor(device)
857
Christian Heimesfaf2f632008-01-06 16:59:19 +0000858 Extract the device minor number from a raw device number (usually the
Georg Brandl116aa622007-08-15 14:28:22 +0000859 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
860
Georg Brandl116aa622007-08-15 14:28:22 +0000861
862.. function:: makedev(major, minor)
863
Christian Heimesfaf2f632008-01-06 16:59:19 +0000864 Compose a raw device number from the major and minor device numbers.
Georg Brandl116aa622007-08-15 14:28:22 +0000865
Georg Brandl116aa622007-08-15 14:28:22 +0000866
867.. function:: mkdir(path[, mode])
868
Georg Brandlf4a41232008-05-26 17:55:52 +0000869 Create a directory named *path* with numeric mode *mode*. The default *mode*
870 is ``0o777`` (octal). On some systems, *mode* is ignored. Where it is used,
Georg Brandlc575c902008-09-13 17:46:05 +0000871 the current umask value is first masked out. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000872
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000873 It is also possible to create temporary directories; see the
874 :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
875
Georg Brandl116aa622007-08-15 14:28:22 +0000876
877.. function:: makedirs(path[, mode])
878
879 .. index::
880 single: directory; creating
881 single: UNC paths; and os.makedirs()
882
883 Recursive directory creation function. Like :func:`mkdir`, but makes all
Georg Brandlf4a41232008-05-26 17:55:52 +0000884 intermediate-level directories needed to contain the leaf directory. Throws
885 an :exc:`error` exception if the leaf directory already exists or cannot be
886 created. The default *mode* is ``0o777`` (octal). On some systems, *mode*
887 is ignored. Where it is used, the current umask value is first masked out.
Georg Brandl116aa622007-08-15 14:28:22 +0000888
889 .. note::
890
891 :func:`makedirs` will become confused if the path elements to create include
Christian Heimesfaf2f632008-01-06 16:59:19 +0000892 :data:`os.pardir`.
Georg Brandl116aa622007-08-15 14:28:22 +0000893
Georg Brandl55ac8f02007-09-01 13:51:09 +0000894 This function handles UNC paths correctly.
Georg Brandl116aa622007-08-15 14:28:22 +0000895
896
897.. function:: pathconf(path, name)
898
899 Return system configuration information relevant to a named file. *name*
900 specifies the configuration value to retrieve; it may be a string which is the
901 name of a defined system value; these names are specified in a number of
902 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
903 additional names as well. The names known to the host operating system are
904 given in the ``pathconf_names`` dictionary. For configuration variables not
905 included in that mapping, passing an integer for *name* is also accepted.
Georg Brandlc575c902008-09-13 17:46:05 +0000906 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000907
908 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
909 specific value for *name* is not supported by the host system, even if it is
910 included in ``pathconf_names``, an :exc:`OSError` is raised with
911 :const:`errno.EINVAL` for the error number.
912
913
914.. data:: pathconf_names
915
916 Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
917 the integer values defined for those names by the host operating system. This
918 can be used to determine the set of names known to the system. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +0000919 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000920
921
922.. function:: readlink(path)
923
924 Return a string representing the path to which the symbolic link points. The
925 result may be either an absolute or relative pathname; if it is relative, it may
926 be converted to an absolute pathname using ``os.path.join(os.path.dirname(path),
927 result)``.
928
Georg Brandl76e55382008-10-08 16:34:57 +0000929 If the *path* is a string object, the result will also be a string object,
930 and the call may raise an UnicodeDecodeError. If the *path* is a bytes
931 object, the result will be a bytes object.
Georg Brandl116aa622007-08-15 14:28:22 +0000932
Georg Brandlc575c902008-09-13 17:46:05 +0000933 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000934
935
936.. function:: remove(path)
937
938 Remove the file *path*. If *path* is a directory, :exc:`OSError` is raised; see
939 :func:`rmdir` below to remove a directory. This is identical to the
940 :func:`unlink` function documented below. On Windows, attempting to remove a
941 file that is in use causes an exception to be raised; on Unix, the directory
942 entry is removed but the storage allocated to the file is not made available
Georg Brandlc575c902008-09-13 17:46:05 +0000943 until the original file is no longer in use. Availability: Unix,
Georg Brandl116aa622007-08-15 14:28:22 +0000944 Windows.
945
946
947.. function:: removedirs(path)
948
949 .. index:: single: directory; deleting
950
Christian Heimesfaf2f632008-01-06 16:59:19 +0000951 Remove directories recursively. Works like :func:`rmdir` except that, if the
Georg Brandl116aa622007-08-15 14:28:22 +0000952 leaf directory is successfully removed, :func:`removedirs` tries to
953 successively remove every parent directory mentioned in *path* until an error
954 is raised (which is ignored, because it generally means that a parent directory
955 is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
956 the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
957 they are empty. Raises :exc:`OSError` if the leaf directory could not be
958 successfully removed.
959
Georg Brandl116aa622007-08-15 14:28:22 +0000960
961.. function:: rename(src, dst)
962
963 Rename the file or directory *src* to *dst*. If *dst* is a directory,
964 :exc:`OSError` will be raised. On Unix, if *dst* exists and is a file, it will
Christian Heimesfaf2f632008-01-06 16:59:19 +0000965 be replaced silently if the user has permission. The operation may fail on some
Georg Brandl116aa622007-08-15 14:28:22 +0000966 Unix flavors if *src* and *dst* are on different filesystems. If successful,
967 the renaming will be an atomic operation (this is a POSIX requirement). On
968 Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a
969 file; there may be no way to implement an atomic rename when *dst* names an
Georg Brandlc575c902008-09-13 17:46:05 +0000970 existing file. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000971
972
973.. function:: renames(old, new)
974
975 Recursive directory or file renaming function. Works like :func:`rename`, except
976 creation of any intermediate directories needed to make the new pathname good is
977 attempted first. After the rename, directories corresponding to rightmost path
978 segments of the old name will be pruned away using :func:`removedirs`.
979
Georg Brandl116aa622007-08-15 14:28:22 +0000980 .. note::
981
982 This function can fail with the new directory structure made if you lack
983 permissions needed to remove the leaf directory or file.
984
985
986.. function:: rmdir(path)
987
Georg Brandlc575c902008-09-13 17:46:05 +0000988 Remove the directory *path*. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000989
990
991.. function:: stat(path)
992
993 Perform a :cfunc:`stat` system call on the given path. The return value is an
994 object whose attributes correspond to the members of the :ctype:`stat`
995 structure, namely: :attr:`st_mode` (protection bits), :attr:`st_ino` (inode
996 number), :attr:`st_dev` (device), :attr:`st_nlink` (number of hard links),
Christian Heimesfaf2f632008-01-06 16:59:19 +0000997 :attr:`st_uid` (user id of owner), :attr:`st_gid` (group id of owner),
Georg Brandl116aa622007-08-15 14:28:22 +0000998 :attr:`st_size` (size of file, in bytes), :attr:`st_atime` (time of most recent
999 access), :attr:`st_mtime` (time of most recent content modification),
1000 :attr:`st_ctime` (platform dependent; time of most recent metadata change on
1001 Unix, or the time of creation on Windows)::
1002
1003 >>> import os
1004 >>> statinfo = os.stat('somefile.txt')
1005 >>> statinfo
1006 (33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
1007 >>> statinfo.st_size
1008 926L
1009 >>>
1010
Georg Brandl116aa622007-08-15 14:28:22 +00001011
1012 On some Unix systems (such as Linux), the following attributes may also be
1013 available: :attr:`st_blocks` (number of blocks allocated for file),
1014 :attr:`st_blksize` (filesystem blocksize), :attr:`st_rdev` (type of device if an
1015 inode device). :attr:`st_flags` (user defined flags for file).
1016
1017 On other Unix systems (such as FreeBSD), the following attributes may be
1018 available (but may be only filled out if root tries to use them): :attr:`st_gen`
1019 (file generation number), :attr:`st_birthtime` (time of file creation).
1020
1021 On Mac OS systems, the following attributes may also be available:
1022 :attr:`st_rsize`, :attr:`st_creator`, :attr:`st_type`.
1023
Georg Brandl116aa622007-08-15 14:28:22 +00001024 .. index:: module: stat
1025
1026 For backward compatibility, the return value of :func:`stat` is also accessible
1027 as a tuple of at least 10 integers giving the most important (and portable)
1028 members of the :ctype:`stat` structure, in the order :attr:`st_mode`,
1029 :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, :attr:`st_uid`,
1030 :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, :attr:`st_mtime`,
1031 :attr:`st_ctime`. More items may be added at the end by some implementations.
1032 The standard module :mod:`stat` defines functions and constants that are useful
1033 for extracting information from a :ctype:`stat` structure. (On Windows, some
1034 items are filled with dummy values.)
1035
1036 .. note::
1037
1038 The exact meaning and resolution of the :attr:`st_atime`, :attr:`st_mtime`, and
1039 :attr:`st_ctime` members depends on the operating system and the file system.
1040 For example, on Windows systems using the FAT or FAT32 file systems,
1041 :attr:`st_mtime` has 2-second resolution, and :attr:`st_atime` has only 1-day
1042 resolution. See your operating system documentation for details.
1043
Georg Brandlc575c902008-09-13 17:46:05 +00001044 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001045
Georg Brandl116aa622007-08-15 14:28:22 +00001046
1047.. function:: stat_float_times([newvalue])
1048
1049 Determine whether :class:`stat_result` represents time stamps as float objects.
1050 If *newvalue* is ``True``, future calls to :func:`stat` return floats, if it is
1051 ``False``, future calls return ints. If *newvalue* is omitted, return the
1052 current setting.
1053
1054 For compatibility with older Python versions, accessing :class:`stat_result` as
1055 a tuple always returns integers.
1056
Georg Brandl55ac8f02007-09-01 13:51:09 +00001057 Python now returns float values by default. Applications which do not work
1058 correctly with floating point time stamps can use this function to restore the
1059 old behaviour.
Georg Brandl116aa622007-08-15 14:28:22 +00001060
1061 The resolution of the timestamps (that is the smallest possible fraction)
1062 depends on the system. Some systems only support second resolution; on these
1063 systems, the fraction will always be zero.
1064
1065 It is recommended that this setting is only changed at program startup time in
1066 the *__main__* module; libraries should never change this setting. If an
1067 application uses a library that works incorrectly if floating point time stamps
1068 are processed, this application should turn the feature off until the library
1069 has been corrected.
1070
1071
1072.. function:: statvfs(path)
1073
1074 Perform a :cfunc:`statvfs` system call on the given path. The return value is
1075 an object whose attributes describe the filesystem on the given path, and
1076 correspond to the members of the :ctype:`statvfs` structure, namely:
1077 :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
1078 :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
1079 :attr:`f_flag`, :attr:`f_namemax`. Availability: Unix.
1080
Georg Brandl116aa622007-08-15 14:28:22 +00001081
Benjamin Peterson5879d412009-03-30 14:51:56 +00001082.. function:: symlink(source, link_name)
Georg Brandl116aa622007-08-15 14:28:22 +00001083
Benjamin Peterson5879d412009-03-30 14:51:56 +00001084 Create a symbolic link pointing to *source* named *link_name*. Availability:
1085 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001086
1087
Georg Brandl116aa622007-08-15 14:28:22 +00001088.. function:: unlink(path)
1089
1090 Remove the file *path*. This is the same function as :func:`remove`; the
Georg Brandlc575c902008-09-13 17:46:05 +00001091 :func:`unlink` name is its traditional Unix name. Availability: Unix,
Georg Brandl116aa622007-08-15 14:28:22 +00001092 Windows.
1093
1094
1095.. function:: utime(path, times)
1096
Benjamin Peterson4cd6a952008-08-17 20:23:46 +00001097 Set the access and modified times of the file specified by *path*. If *times*
1098 is ``None``, then the file's access and modified times are set to the current
1099 time. (The effect is similar to running the Unix program :program:`touch` on
1100 the path.) Otherwise, *times* must be a 2-tuple of numbers, of the form
1101 ``(atime, mtime)`` which is used to set the access and modified times,
1102 respectively. Whether a directory can be given for *path* depends on whether
1103 the operating system implements directories as files (for example, Windows
1104 does not). Note that the exact times you set here may not be returned by a
1105 subsequent :func:`stat` call, depending on the resolution with which your
1106 operating system records access and modification times; see :func:`stat`.
Georg Brandl116aa622007-08-15 14:28:22 +00001107
Georg Brandlc575c902008-09-13 17:46:05 +00001108 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001109
1110
1111.. function:: walk(top[, topdown=True [, onerror=None[, followlinks=False]]])
1112
1113 .. index::
1114 single: directory; walking
1115 single: directory; traversal
1116
Christian Heimesfaf2f632008-01-06 16:59:19 +00001117 Generate the file names in a directory tree by walking the tree
1118 either top-down or bottom-up. For each directory in the tree rooted at directory
Georg Brandl116aa622007-08-15 14:28:22 +00001119 *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
1120 filenames)``.
1121
1122 *dirpath* is a string, the path to the directory. *dirnames* is a list of the
1123 names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``).
1124 *filenames* is a list of the names of the non-directory files in *dirpath*.
1125 Note that the names in the lists contain no path components. To get a full path
1126 (which begins with *top*) to a file or directory in *dirpath*, do
1127 ``os.path.join(dirpath, name)``.
1128
Christian Heimesfaf2f632008-01-06 16:59:19 +00001129 If optional argument *topdown* is ``True`` or not specified, the triple for a
Georg Brandl116aa622007-08-15 14:28:22 +00001130 directory is generated before the triples for any of its subdirectories
Christian Heimesfaf2f632008-01-06 16:59:19 +00001131 (directories are generated top-down). If *topdown* is ``False``, the triple for a
Georg Brandl116aa622007-08-15 14:28:22 +00001132 directory is generated after the triples for all of its subdirectories
Christian Heimesfaf2f632008-01-06 16:59:19 +00001133 (directories are generated bottom-up).
Georg Brandl116aa622007-08-15 14:28:22 +00001134
Christian Heimesfaf2f632008-01-06 16:59:19 +00001135 When *topdown* is ``True``, the caller can modify the *dirnames* list in-place
Georg Brandl116aa622007-08-15 14:28:22 +00001136 (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
1137 recurse into the subdirectories whose names remain in *dirnames*; this can be
1138 used to prune the search, impose a specific order of visiting, or even to inform
1139 :func:`walk` about directories the caller creates or renames before it resumes
Christian Heimesfaf2f632008-01-06 16:59:19 +00001140 :func:`walk` again. Modifying *dirnames* when *topdown* is ``False`` is
Georg Brandl116aa622007-08-15 14:28:22 +00001141 ineffective, because in bottom-up mode the directories in *dirnames* are
1142 generated before *dirpath* itself is generated.
1143
Christian Heimesfaf2f632008-01-06 16:59:19 +00001144 By default errors from the :func:`listdir` call are ignored. If optional
Georg Brandl116aa622007-08-15 14:28:22 +00001145 argument *onerror* is specified, it should be a function; it will be called with
1146 one argument, an :exc:`OSError` instance. It can report the error to continue
1147 with the walk, or raise the exception to abort the walk. Note that the filename
1148 is available as the ``filename`` attribute of the exception object.
1149
1150 By default, :func:`walk` will not walk down into symbolic links that resolve to
Christian Heimesfaf2f632008-01-06 16:59:19 +00001151 directories. Set *followlinks* to ``True`` to visit directories pointed to by
Georg Brandl116aa622007-08-15 14:28:22 +00001152 symlinks, on systems that support them.
1153
Georg Brandl116aa622007-08-15 14:28:22 +00001154 .. note::
1155
Christian Heimesfaf2f632008-01-06 16:59:19 +00001156 Be aware that setting *followlinks* to ``True`` can lead to infinite recursion if a
Georg Brandl116aa622007-08-15 14:28:22 +00001157 link points to a parent directory of itself. :func:`walk` does not keep track of
1158 the directories it visited already.
1159
1160 .. note::
1161
1162 If you pass a relative pathname, don't change the current working directory
1163 between resumptions of :func:`walk`. :func:`walk` never changes the current
1164 directory, and assumes that its caller doesn't either.
1165
1166 This example displays the number of bytes taken by non-directory files in each
1167 directory under the starting directory, except that it doesn't look under any
1168 CVS subdirectory::
1169
1170 import os
1171 from os.path import join, getsize
1172 for root, dirs, files in os.walk('python/Lib/email'):
Georg Brandl6911e3c2007-09-04 07:15:32 +00001173 print(root, "consumes", end=" ")
1174 print(sum(getsize(join(root, name)) for name in files), end=" ")
1175 print("bytes in", len(files), "non-directory files")
Georg Brandl116aa622007-08-15 14:28:22 +00001176 if 'CVS' in dirs:
1177 dirs.remove('CVS') # don't visit CVS directories
1178
Christian Heimesfaf2f632008-01-06 16:59:19 +00001179 In the next example, walking the tree bottom-up is essential: :func:`rmdir`
Georg Brandl116aa622007-08-15 14:28:22 +00001180 doesn't allow deleting a directory before the directory is empty::
1181
Christian Heimesfaf2f632008-01-06 16:59:19 +00001182 # Delete everything reachable from the directory named in "top",
Georg Brandl116aa622007-08-15 14:28:22 +00001183 # assuming there are no symbolic links.
1184 # CAUTION: This is dangerous! For example, if top == '/', it
1185 # could delete all your disk files.
1186 import os
1187 for root, dirs, files in os.walk(top, topdown=False):
1188 for name in files:
1189 os.remove(os.path.join(root, name))
1190 for name in dirs:
1191 os.rmdir(os.path.join(root, name))
1192
Georg Brandl116aa622007-08-15 14:28:22 +00001193
1194.. _os-process:
1195
1196Process Management
1197------------------
1198
1199These functions may be used to create and manage processes.
1200
1201The various :func:`exec\*` functions take a list of arguments for the new
1202program loaded into the process. In each case, the first of these arguments is
1203passed to the new program as its own name rather than as an argument a user may
1204have typed on a command line. For the C programmer, this is the ``argv[0]``
1205passed to a program's :cfunc:`main`. For example, ``os.execv('/bin/echo',
1206['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
1207to be ignored.
1208
1209
1210.. function:: abort()
1211
1212 Generate a :const:`SIGABRT` signal to the current process. On Unix, the default
1213 behavior is to produce a core dump; on Windows, the process immediately returns
1214 an exit code of ``3``. Be aware that programs which use :func:`signal.signal`
1215 to register a handler for :const:`SIGABRT` will behave differently.
Georg Brandlc575c902008-09-13 17:46:05 +00001216 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001217
1218
1219.. function:: execl(path, arg0, arg1, ...)
1220 execle(path, arg0, arg1, ..., env)
1221 execlp(file, arg0, arg1, ...)
1222 execlpe(file, arg0, arg1, ..., env)
1223 execv(path, args)
1224 execve(path, args, env)
1225 execvp(file, args)
1226 execvpe(file, args, env)
1227
1228 These functions all execute a new program, replacing the current process; they
1229 do not return. On Unix, the new executable is loaded into the current process,
Christian Heimesfaf2f632008-01-06 16:59:19 +00001230 and will have the same process id as the caller. Errors will be reported as
Georg Brandl48310cd2009-01-03 21:18:54 +00001231 :exc:`OSError` exceptions.
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001232
1233 The current process is replaced immediately. Open file objects and
1234 descriptors are not flushed, so if there may be data buffered
1235 on these open files, you should flush them using
1236 :func:`sys.stdout.flush` or :func:`os.fsync` before calling an
1237 :func:`exec\*` function.
Georg Brandl116aa622007-08-15 14:28:22 +00001238
Christian Heimesfaf2f632008-01-06 16:59:19 +00001239 The "l" and "v" variants of the :func:`exec\*` functions differ in how
1240 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl116aa622007-08-15 14:28:22 +00001241 to work with if the number of parameters is fixed when the code is written; the
1242 individual parameters simply become additional parameters to the :func:`execl\*`
Christian Heimesfaf2f632008-01-06 16:59:19 +00001243 functions. The "v" variants are good when the number of parameters is
Georg Brandl116aa622007-08-15 14:28:22 +00001244 variable, with the arguments being passed in a list or tuple as the *args*
1245 parameter. In either case, the arguments to the child process should start with
1246 the name of the command being run, but this is not enforced.
1247
Christian Heimesfaf2f632008-01-06 16:59:19 +00001248 The variants which include a "p" near the end (:func:`execlp`,
Georg Brandl116aa622007-08-15 14:28:22 +00001249 :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
1250 :envvar:`PATH` environment variable to locate the program *file*. When the
1251 environment is being replaced (using one of the :func:`exec\*e` variants,
1252 discussed in the next paragraph), the new environment is used as the source of
1253 the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
1254 :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
1255 locate the executable; *path* must contain an appropriate absolute or relative
1256 path.
1257
1258 For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
Christian Heimesfaf2f632008-01-06 16:59:19 +00001259 that these all end in "e"), the *env* parameter must be a mapping which is
Christian Heimesa342c012008-04-20 21:01:16 +00001260 used to define the environment variables for the new process (these are used
1261 instead of the current process' environment); the functions :func:`execl`,
Georg Brandl116aa622007-08-15 14:28:22 +00001262 :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
Georg Brandl48310cd2009-01-03 21:18:54 +00001263 inherit the environment of the current process.
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001264
1265 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001266
1267
1268.. function:: _exit(n)
1269
1270 Exit to the system with status *n*, without calling cleanup handlers, flushing
Georg Brandlc575c902008-09-13 17:46:05 +00001271 stdio buffers, etc. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001272
1273 .. note::
1274
1275 The standard way to exit is ``sys.exit(n)``. :func:`_exit` should normally only
1276 be used in the child process after a :func:`fork`.
1277
Christian Heimesfaf2f632008-01-06 16:59:19 +00001278The following exit codes are defined and can be used with :func:`_exit`,
Georg Brandl116aa622007-08-15 14:28:22 +00001279although they are not required. These are typically used for system programs
1280written in Python, such as a mail server's external command delivery program.
1281
1282.. note::
1283
1284 Some of these may not be available on all Unix platforms, since there is some
1285 variation. These constants are defined where they are defined by the underlying
1286 platform.
1287
1288
1289.. data:: EX_OK
1290
Georg Brandlc575c902008-09-13 17:46:05 +00001291 Exit code that means no error occurred. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001292
Georg Brandl116aa622007-08-15 14:28:22 +00001293
1294.. data:: EX_USAGE
1295
1296 Exit code that means the command was used incorrectly, such as when the wrong
Georg Brandlc575c902008-09-13 17:46:05 +00001297 number of arguments are given. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001298
Georg Brandl116aa622007-08-15 14:28:22 +00001299
1300.. data:: EX_DATAERR
1301
Georg Brandlc575c902008-09-13 17:46:05 +00001302 Exit code that means the input data was incorrect. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001303
Georg Brandl116aa622007-08-15 14:28:22 +00001304
1305.. data:: EX_NOINPUT
1306
1307 Exit code that means an input file did not exist or was not readable.
Georg Brandlc575c902008-09-13 17:46:05 +00001308 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001309
Georg Brandl116aa622007-08-15 14:28:22 +00001310
1311.. data:: EX_NOUSER
1312
Georg Brandlc575c902008-09-13 17:46:05 +00001313 Exit code that means a specified user did not exist. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001314
Georg Brandl116aa622007-08-15 14:28:22 +00001315
1316.. data:: EX_NOHOST
1317
Georg Brandlc575c902008-09-13 17:46:05 +00001318 Exit code that means a specified host did not exist. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001319
Georg Brandl116aa622007-08-15 14:28:22 +00001320
1321.. data:: EX_UNAVAILABLE
1322
1323 Exit code that means that a required service is unavailable. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +00001324 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001325
Georg Brandl116aa622007-08-15 14:28:22 +00001326
1327.. data:: EX_SOFTWARE
1328
1329 Exit code that means an internal software error was detected. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +00001330 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001331
Georg Brandl116aa622007-08-15 14:28:22 +00001332
1333.. data:: EX_OSERR
1334
1335 Exit code that means an operating system error was detected, such as the
Georg Brandlc575c902008-09-13 17:46:05 +00001336 inability to fork or create a pipe. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001337
Georg Brandl116aa622007-08-15 14:28:22 +00001338
1339.. data:: EX_OSFILE
1340
1341 Exit code that means some system file did not exist, could not be opened, or had
Georg Brandlc575c902008-09-13 17:46:05 +00001342 some other kind of error. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001343
Georg Brandl116aa622007-08-15 14:28:22 +00001344
1345.. data:: EX_CANTCREAT
1346
1347 Exit code that means a user specified output file could not be created.
Georg Brandlc575c902008-09-13 17:46:05 +00001348 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001349
Georg Brandl116aa622007-08-15 14:28:22 +00001350
1351.. data:: EX_IOERR
1352
1353 Exit code that means that an error occurred while doing I/O on some file.
Georg Brandlc575c902008-09-13 17:46:05 +00001354 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001355
Georg Brandl116aa622007-08-15 14:28:22 +00001356
1357.. data:: EX_TEMPFAIL
1358
1359 Exit code that means a temporary failure occurred. This indicates something
1360 that may not really be an error, such as a network connection that couldn't be
Georg Brandlc575c902008-09-13 17:46:05 +00001361 made during a retryable operation. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001362
Georg Brandl116aa622007-08-15 14:28:22 +00001363
1364.. data:: EX_PROTOCOL
1365
1366 Exit code that means that a protocol exchange was illegal, invalid, or not
Georg Brandlc575c902008-09-13 17:46:05 +00001367 understood. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001368
Georg Brandl116aa622007-08-15 14:28:22 +00001369
1370.. data:: EX_NOPERM
1371
1372 Exit code that means that there were insufficient permissions to perform the
Georg Brandlc575c902008-09-13 17:46:05 +00001373 operation (but not intended for file system problems). Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001374
Georg Brandl116aa622007-08-15 14:28:22 +00001375
1376.. data:: EX_CONFIG
1377
1378 Exit code that means that some kind of configuration error occurred.
Georg Brandlc575c902008-09-13 17:46:05 +00001379 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001380
Georg Brandl116aa622007-08-15 14:28:22 +00001381
1382.. data:: EX_NOTFOUND
1383
1384 Exit code that means something like "an entry was not found". Availability:
Georg Brandlc575c902008-09-13 17:46:05 +00001385 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001386
Georg Brandl116aa622007-08-15 14:28:22 +00001387
1388.. function:: fork()
1389
Christian Heimesfaf2f632008-01-06 16:59:19 +00001390 Fork a child process. Return ``0`` in the child and the child's process id in the
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001391 parent. If an error occurs :exc:`OSError` is raised.
Benjamin Petersonbcd8ac32008-10-10 22:20:52 +00001392
1393 Note that some platforms including FreeBSD <= 6.3, Cygwin and OS/2 EMX have
1394 known issues when using fork() from a thread.
1395
Georg Brandlc575c902008-09-13 17:46:05 +00001396 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001397
1398
1399.. function:: forkpty()
1400
1401 Fork a child process, using a new pseudo-terminal as the child's controlling
1402 terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
1403 new child's process id in the parent, and *fd* is the file descriptor of the
1404 master end of the pseudo-terminal. For a more portable approach, use the
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001405 :mod:`pty` module. If an error occurs :exc:`OSError` is raised.
Georg Brandlc575c902008-09-13 17:46:05 +00001406 Availability: some flavors of Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001407
1408
1409.. function:: kill(pid, sig)
1410
1411 .. index::
1412 single: process; killing
1413 single: process; signalling
1414
1415 Send signal *sig* to the process *pid*. Constants for the specific signals
1416 available on the host platform are defined in the :mod:`signal` module.
Georg Brandlc575c902008-09-13 17:46:05 +00001417 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001418
1419
1420.. function:: killpg(pgid, sig)
1421
1422 .. index::
1423 single: process; killing
1424 single: process; signalling
1425
Georg Brandlc575c902008-09-13 17:46:05 +00001426 Send the signal *sig* to the process group *pgid*. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001427
Georg Brandl116aa622007-08-15 14:28:22 +00001428
1429.. function:: nice(increment)
1430
1431 Add *increment* to the process's "niceness". Return the new niceness.
Georg Brandlc575c902008-09-13 17:46:05 +00001432 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001433
1434
1435.. function:: plock(op)
1436
1437 Lock program segments into memory. The value of *op* (defined in
Georg Brandlc575c902008-09-13 17:46:05 +00001438 ``<sys/lock.h>``) determines which segments are locked. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001439
1440
1441.. function:: popen(...)
1442 :noindex:
1443
1444 Run child processes, returning opened pipes for communications. These functions
1445 are described in section :ref:`os-newstreams`.
1446
1447
1448.. function:: spawnl(mode, path, ...)
1449 spawnle(mode, path, ..., env)
1450 spawnlp(mode, file, ...)
1451 spawnlpe(mode, file, ..., env)
1452 spawnv(mode, path, args)
1453 spawnve(mode, path, args, env)
1454 spawnvp(mode, file, args)
1455 spawnvpe(mode, file, args, env)
1456
1457 Execute the program *path* in a new process.
1458
1459 (Note that the :mod:`subprocess` module provides more powerful facilities for
1460 spawning new processes and retrieving their results; using that module is
Georg Brandl48310cd2009-01-03 21:18:54 +00001461 preferable to using these functions. Check specially the *Replacing Older
Benjamin Petersondcf97b92008-07-02 17:30:14 +00001462 Functions with the subprocess Module* section in that documentation page.)
Georg Brandl116aa622007-08-15 14:28:22 +00001463
Christian Heimesfaf2f632008-01-06 16:59:19 +00001464 If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new
Georg Brandl116aa622007-08-15 14:28:22 +00001465 process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
1466 exits normally, or ``-signal``, where *signal* is the signal that killed the
Christian Heimesfaf2f632008-01-06 16:59:19 +00001467 process. On Windows, the process id will actually be the process handle, so can
Georg Brandl116aa622007-08-15 14:28:22 +00001468 be used with the :func:`waitpid` function.
1469
Christian Heimesfaf2f632008-01-06 16:59:19 +00001470 The "l" and "v" variants of the :func:`spawn\*` functions differ in how
1471 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl116aa622007-08-15 14:28:22 +00001472 to work with if the number of parameters is fixed when the code is written; the
1473 individual parameters simply become additional parameters to the
Christian Heimesfaf2f632008-01-06 16:59:19 +00001474 :func:`spawnl\*` functions. The "v" variants are good when the number of
Georg Brandl116aa622007-08-15 14:28:22 +00001475 parameters is variable, with the arguments being passed in a list or tuple as
1476 the *args* parameter. In either case, the arguments to the child process must
1477 start with the name of the command being run.
1478
Christian Heimesfaf2f632008-01-06 16:59:19 +00001479 The variants which include a second "p" near the end (:func:`spawnlp`,
Georg Brandl116aa622007-08-15 14:28:22 +00001480 :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
1481 :envvar:`PATH` environment variable to locate the program *file*. When the
1482 environment is being replaced (using one of the :func:`spawn\*e` variants,
1483 discussed in the next paragraph), the new environment is used as the source of
1484 the :envvar:`PATH` variable. The other variants, :func:`spawnl`,
1485 :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
1486 :envvar:`PATH` variable to locate the executable; *path* must contain an
1487 appropriate absolute or relative path.
1488
1489 For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
Christian Heimesfaf2f632008-01-06 16:59:19 +00001490 (note that these all end in "e"), the *env* parameter must be a mapping
Christian Heimesa342c012008-04-20 21:01:16 +00001491 which is used to define the environment variables for the new process (they are
1492 used instead of the current process' environment); the functions
Georg Brandl116aa622007-08-15 14:28:22 +00001493 :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
1494 the new process to inherit the environment of the current process.
1495
1496 As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are
1497 equivalent::
1498
1499 import os
1500 os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
1501
1502 L = ['cp', 'index.html', '/dev/null']
1503 os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
1504
1505 Availability: Unix, Windows. :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
1506 and :func:`spawnvpe` are not available on Windows.
1507
Georg Brandl116aa622007-08-15 14:28:22 +00001508
1509.. data:: P_NOWAIT
1510 P_NOWAITO
1511
1512 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1513 functions. If either of these values is given, the :func:`spawn\*` functions
Christian Heimesfaf2f632008-01-06 16:59:19 +00001514 will return as soon as the new process has been created, with the process id as
Georg Brandlc575c902008-09-13 17:46:05 +00001515 the return value. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001516
Georg Brandl116aa622007-08-15 14:28:22 +00001517
1518.. data:: P_WAIT
1519
1520 Possible value for the *mode* parameter to the :func:`spawn\*` family of
1521 functions. If this is given as *mode*, the :func:`spawn\*` functions will not
1522 return until the new process has run to completion and will return the exit code
1523 of the process the run is successful, or ``-signal`` if a signal kills the
Georg Brandlc575c902008-09-13 17:46:05 +00001524 process. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001525
Georg Brandl116aa622007-08-15 14:28:22 +00001526
1527.. data:: P_DETACH
1528 P_OVERLAY
1529
1530 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1531 functions. These are less portable than those listed above. :const:`P_DETACH`
1532 is similar to :const:`P_NOWAIT`, but the new process is detached from the
1533 console of the calling process. If :const:`P_OVERLAY` is used, the current
1534 process will be replaced; the :func:`spawn\*` function will not return.
1535 Availability: Windows.
1536
Georg Brandl116aa622007-08-15 14:28:22 +00001537
1538.. function:: startfile(path[, operation])
1539
1540 Start a file with its associated application.
1541
1542 When *operation* is not specified or ``'open'``, this acts like double-clicking
1543 the file in Windows Explorer, or giving the file name as an argument to the
1544 :program:`start` command from the interactive command shell: the file is opened
1545 with whatever application (if any) its extension is associated.
1546
1547 When another *operation* is given, it must be a "command verb" that specifies
1548 what should be done with the file. Common verbs documented by Microsoft are
1549 ``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` and
1550 ``'find'`` (to be used on directories).
1551
1552 :func:`startfile` returns as soon as the associated application is launched.
1553 There is no option to wait for the application to close, and no way to retrieve
1554 the application's exit status. The *path* parameter is relative to the current
1555 directory. If you want to use an absolute path, make sure the first character
1556 is not a slash (``'/'``); the underlying Win32 :cfunc:`ShellExecute` function
1557 doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that
1558 the path is properly encoded for Win32. Availability: Windows.
1559
Georg Brandl116aa622007-08-15 14:28:22 +00001560
1561.. function:: system(command)
1562
1563 Execute the command (a string) in a subshell. This is implemented by calling
1564 the Standard C function :cfunc:`system`, and has the same limitations. Changes
Christian Heimesfaf2f632008-01-06 16:59:19 +00001565 to :data:`os.environ`, :data:`sys.stdin`, etc. are not reflected in the
1566 environment of the executed command.
Georg Brandl116aa622007-08-15 14:28:22 +00001567
1568 On Unix, the return value is the exit status of the process encoded in the
1569 format specified for :func:`wait`. Note that POSIX does not specify the meaning
1570 of the return value of the C :cfunc:`system` function, so the return value of
1571 the Python function is system-dependent.
1572
1573 On Windows, the return value is that returned by the system shell after running
1574 *command*, given by the Windows environment variable :envvar:`COMSPEC`: on
1575 :program:`command.com` systems (Windows 95, 98 and ME) this is always ``0``; on
1576 :program:`cmd.exe` systems (Windows NT, 2000 and XP) this is the exit status of
1577 the command run; on systems using a non-native shell, consult your shell
1578 documentation.
1579
Georg Brandlc575c902008-09-13 17:46:05 +00001580 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001581
1582 The :mod:`subprocess` module provides more powerful facilities for spawning new
1583 processes and retrieving their results; using that module is preferable to using
Benjamin Petersondcf97b92008-07-02 17:30:14 +00001584 this function. Use the :mod:`subprocess` module. Check especially the
1585 :ref:`subprocess-replacements` section.
Georg Brandl116aa622007-08-15 14:28:22 +00001586
1587
1588.. function:: times()
1589
1590 Return a 5-tuple of floating point numbers indicating accumulated (processor or
1591 other) times, in seconds. The items are: user time, system time, children's
1592 user time, children's system time, and elapsed real time since a fixed point in
1593 the past, in that order. See the Unix manual page :manpage:`times(2)` or the
Georg Brandlc575c902008-09-13 17:46:05 +00001594 corresponding Windows Platform API documentation. Availability: Unix,
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001595 Windows. On Windows, only the first two items are filled, the others are zero.
Georg Brandl116aa622007-08-15 14:28:22 +00001596
1597
1598.. function:: wait()
1599
1600 Wait for completion of a child process, and return a tuple containing its pid
1601 and exit status indication: a 16-bit number, whose low byte is the signal number
1602 that killed the process, and whose high byte is the exit status (if the signal
1603 number is zero); the high bit of the low byte is set if a core file was
Georg Brandlc575c902008-09-13 17:46:05 +00001604 produced. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001605
1606
1607.. function:: waitpid(pid, options)
1608
1609 The details of this function differ on Unix and Windows.
1610
1611 On Unix: Wait for completion of a child process given by process id *pid*, and
1612 return a tuple containing its process id and exit status indication (encoded as
1613 for :func:`wait`). The semantics of the call are affected by the value of the
1614 integer *options*, which should be ``0`` for normal operation.
1615
1616 If *pid* is greater than ``0``, :func:`waitpid` requests status information for
1617 that specific process. If *pid* is ``0``, the request is for the status of any
1618 child in the process group of the current process. If *pid* is ``-1``, the
1619 request pertains to any child of the current process. If *pid* is less than
1620 ``-1``, status is requested for any process in the process group ``-pid`` (the
1621 absolute value of *pid*).
1622
Benjamin Peterson4cd6a952008-08-17 20:23:46 +00001623 An :exc:`OSError` is raised with the value of errno when the syscall
1624 returns -1.
1625
Georg Brandl116aa622007-08-15 14:28:22 +00001626 On Windows: Wait for completion of a process given by process handle *pid*, and
1627 return a tuple containing *pid*, and its exit status shifted left by 8 bits
1628 (shifting makes cross-platform use of the function easier). A *pid* less than or
1629 equal to ``0`` has no special meaning on Windows, and raises an exception. The
1630 value of integer *options* has no effect. *pid* can refer to any process whose
1631 id is known, not necessarily a child process. The :func:`spawn` functions called
1632 with :const:`P_NOWAIT` return suitable process handles.
1633
1634
1635.. function:: wait3([options])
1636
1637 Similar to :func:`waitpid`, except no process id argument is given and a
1638 3-element tuple containing the child's process id, exit status indication, and
1639 resource usage information is returned. Refer to :mod:`resource`.\
1640 :func:`getrusage` for details on resource usage information. The option
1641 argument is the same as that provided to :func:`waitpid` and :func:`wait4`.
1642 Availability: Unix.
1643
Georg Brandl116aa622007-08-15 14:28:22 +00001644
1645.. function:: wait4(pid, options)
1646
1647 Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
1648 process id, exit status indication, and resource usage information is returned.
1649 Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage
1650 information. The arguments to :func:`wait4` are the same as those provided to
1651 :func:`waitpid`. Availability: Unix.
1652
Georg Brandl116aa622007-08-15 14:28:22 +00001653
1654.. data:: WNOHANG
1655
1656 The option for :func:`waitpid` to return immediately if no child process status
1657 is available immediately. The function returns ``(0, 0)`` in this case.
Georg Brandlc575c902008-09-13 17:46:05 +00001658 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001659
1660
1661.. data:: WCONTINUED
1662
1663 This option causes child processes to be reported if they have been continued
1664 from a job control stop since their status was last reported. Availability: Some
1665 Unix systems.
1666
Georg Brandl116aa622007-08-15 14:28:22 +00001667
1668.. data:: WUNTRACED
1669
1670 This option causes child processes to be reported if they have been stopped but
1671 their current state has not been reported since they were stopped. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +00001672 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001673
Georg Brandl116aa622007-08-15 14:28:22 +00001674
1675The following functions take a process status code as returned by
1676:func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be
1677used to determine the disposition of a process.
1678
Georg Brandl116aa622007-08-15 14:28:22 +00001679.. function:: WCOREDUMP(status)
1680
Christian Heimesfaf2f632008-01-06 16:59:19 +00001681 Return ``True`` if a core dump was generated for the process, otherwise
Georg Brandlc575c902008-09-13 17:46:05 +00001682 return ``False``. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001683
Georg Brandl116aa622007-08-15 14:28:22 +00001684
1685.. function:: WIFCONTINUED(status)
1686
Christian Heimesfaf2f632008-01-06 16:59:19 +00001687 Return ``True`` if the process has been continued from a job control stop,
1688 otherwise return ``False``. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001689
Georg Brandl116aa622007-08-15 14:28:22 +00001690
1691.. function:: WIFSTOPPED(status)
1692
Christian Heimesfaf2f632008-01-06 16:59:19 +00001693 Return ``True`` if the process has been stopped, otherwise return
Georg Brandl116aa622007-08-15 14:28:22 +00001694 ``False``. Availability: Unix.
1695
1696
1697.. function:: WIFSIGNALED(status)
1698
Christian Heimesfaf2f632008-01-06 16:59:19 +00001699 Return ``True`` if the process exited due to a signal, otherwise return
Georg Brandlc575c902008-09-13 17:46:05 +00001700 ``False``. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001701
1702
1703.. function:: WIFEXITED(status)
1704
Christian Heimesfaf2f632008-01-06 16:59:19 +00001705 Return ``True`` if the process exited using the :manpage:`exit(2)` system call,
Georg Brandlc575c902008-09-13 17:46:05 +00001706 otherwise return ``False``. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001707
1708
1709.. function:: WEXITSTATUS(status)
1710
1711 If ``WIFEXITED(status)`` is true, return the integer parameter to the
1712 :manpage:`exit(2)` system call. Otherwise, the return value is meaningless.
Georg Brandlc575c902008-09-13 17:46:05 +00001713 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001714
1715
1716.. function:: WSTOPSIG(status)
1717
Georg Brandlc575c902008-09-13 17:46:05 +00001718 Return the signal which caused the process to stop. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001719
1720
1721.. function:: WTERMSIG(status)
1722
Georg Brandlc575c902008-09-13 17:46:05 +00001723 Return the signal which caused the process to exit. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001724
1725
1726.. _os-path:
1727
1728Miscellaneous System Information
1729--------------------------------
1730
1731
1732.. function:: confstr(name)
1733
1734 Return string-valued system configuration values. *name* specifies the
1735 configuration value to retrieve; it may be a string which is the name of a
1736 defined system value; these names are specified in a number of standards (POSIX,
1737 Unix 95, Unix 98, and others). Some platforms define additional names as well.
1738 The names known to the host operating system are given as the keys of the
1739 ``confstr_names`` dictionary. For configuration variables not included in that
1740 mapping, passing an integer for *name* is also accepted. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +00001741 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001742
1743 If the configuration value specified by *name* isn't defined, ``None`` is
1744 returned.
1745
1746 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
1747 specific value for *name* is not supported by the host system, even if it is
1748 included in ``confstr_names``, an :exc:`OSError` is raised with
1749 :const:`errno.EINVAL` for the error number.
1750
1751
1752.. data:: confstr_names
1753
1754 Dictionary mapping names accepted by :func:`confstr` to the integer values
1755 defined for those names by the host operating system. This can be used to
Georg Brandlc575c902008-09-13 17:46:05 +00001756 determine the set of names known to the system. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001757
1758
1759.. function:: getloadavg()
1760
Christian Heimesa62da1d2008-01-12 19:39:10 +00001761 Return the number of processes in the system run queue averaged over the last
1762 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was
Georg Brandlf08a9dd2008-06-10 16:57:31 +00001763 unobtainable. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001764
Georg Brandl116aa622007-08-15 14:28:22 +00001765
1766.. function:: sysconf(name)
1767
1768 Return integer-valued system configuration values. If the configuration value
1769 specified by *name* isn't defined, ``-1`` is returned. The comments regarding
1770 the *name* parameter for :func:`confstr` apply here as well; the dictionary that
1771 provides information on the known names is given by ``sysconf_names``.
Georg Brandlc575c902008-09-13 17:46:05 +00001772 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001773
1774
1775.. data:: sysconf_names
1776
1777 Dictionary mapping names accepted by :func:`sysconf` to the integer values
1778 defined for those names by the host operating system. This can be used to
Georg Brandlc575c902008-09-13 17:46:05 +00001779 determine the set of names known to the system. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001780
Christian Heimesfaf2f632008-01-06 16:59:19 +00001781The following data values are used to support path manipulation operations. These
Georg Brandl116aa622007-08-15 14:28:22 +00001782are defined for all platforms.
1783
1784Higher-level operations on pathnames are defined in the :mod:`os.path` module.
1785
1786
1787.. data:: curdir
1788
1789 The constant string used by the operating system to refer to the current
Georg Brandlc575c902008-09-13 17:46:05 +00001790 directory. This is ``'.'`` for Windows and POSIX. Also available via
1791 :mod:`os.path`.
Georg Brandl116aa622007-08-15 14:28:22 +00001792
1793
1794.. data:: pardir
1795
1796 The constant string used by the operating system to refer to the parent
Georg Brandlc575c902008-09-13 17:46:05 +00001797 directory. This is ``'..'`` for Windows and POSIX. Also available via
1798 :mod:`os.path`.
Georg Brandl116aa622007-08-15 14:28:22 +00001799
1800
1801.. data:: sep
1802
Georg Brandlc575c902008-09-13 17:46:05 +00001803 The character used by the operating system to separate pathname components.
1804 This is ``'/'`` for POSIX and ``'\\'`` for Windows. Note that knowing this
1805 is not sufficient to be able to parse or concatenate pathnames --- use
Georg Brandl116aa622007-08-15 14:28:22 +00001806 :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
1807 useful. Also available via :mod:`os.path`.
1808
1809
1810.. data:: altsep
1811
1812 An alternative character used by the operating system to separate pathname
1813 components, or ``None`` if only one separator character exists. This is set to
1814 ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
1815 :mod:`os.path`.
1816
1817
1818.. data:: extsep
1819
1820 The character which separates the base filename from the extension; for example,
1821 the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.
1822
Georg Brandl116aa622007-08-15 14:28:22 +00001823
1824.. data:: pathsep
1825
1826 The character conventionally used by the operating system to separate search
1827 path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
1828 Windows. Also available via :mod:`os.path`.
1829
1830
1831.. data:: defpath
1832
1833 The default search path used by :func:`exec\*p\*` and :func:`spawn\*p\*` if the
1834 environment doesn't have a ``'PATH'`` key. Also available via :mod:`os.path`.
1835
1836
1837.. data:: linesep
1838
1839 The string used to separate (or, rather, terminate) lines on the current
Georg Brandlc575c902008-09-13 17:46:05 +00001840 platform. This may be a single character, such as ``'\n'`` for POSIX, or
1841 multiple characters, for example, ``'\r\n'`` for Windows. Do not use
1842 *os.linesep* as a line terminator when writing files opened in text mode (the
1843 default); use a single ``'\n'`` instead, on all platforms.
Georg Brandl116aa622007-08-15 14:28:22 +00001844
1845
1846.. data:: devnull
1847
Georg Brandlc575c902008-09-13 17:46:05 +00001848 The file path of the null device. For example: ``'/dev/null'`` for POSIX.
1849 Also available via :mod:`os.path`.
Georg Brandl116aa622007-08-15 14:28:22 +00001850
Georg Brandl116aa622007-08-15 14:28:22 +00001851
1852.. _os-miscfunc:
1853
1854Miscellaneous Functions
1855-----------------------
1856
1857
1858.. function:: urandom(n)
1859
1860 Return a string of *n* random bytes suitable for cryptographic use.
1861
1862 This function returns random bytes from an OS-specific randomness source. The
1863 returned data should be unpredictable enough for cryptographic applications,
1864 though its exact quality depends on the OS implementation. On a UNIX-like
1865 system this will query /dev/urandom, and on Windows it will use CryptGenRandom.
1866 If a randomness source is not found, :exc:`NotImplementedError` will be raised.