blob: 2cd9dde358abb4af34ed761cf8775bd0e4f73e8d [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
Benjamin Peterson68dbebc2009-12-31 03:30:26 +000016Notes on the availability of these functions:
Georg Brandl116aa622007-08-15 14:28:22 +000017
Benjamin Peterson68dbebc2009-12-31 03:30:26 +000018* The design of all built-in operating system dependent modules of Python is
19 such that as long as the same functionality is available, it uses the same
20 interface; for example, the function ``os.stat(path)`` returns stat
21 information about *path* in the same format (which happens to have originated
22 with the POSIX interface).
Georg Brandl116aa622007-08-15 14:28:22 +000023
Benjamin Peterson68dbebc2009-12-31 03:30:26 +000024* Extensions peculiar to a particular operating system are also available
25 through the :mod:`os` module, but using them is of course a threat to
26 portability.
Georg Brandl116aa622007-08-15 14:28:22 +000027
Benjamin Peterson68dbebc2009-12-31 03:30:26 +000028* All functions accepting path or file names accept both bytes and string
29 objects, and result in an object of the same type, if a path or file name is
30 returned.
Georg Brandl76e55382008-10-08 16:34:57 +000031
32.. note::
33
Georg Brandlc575c902008-09-13 17:46:05 +000034 If not separately noted, all functions that claim "Availability: Unix" are
35 supported on Mac OS X, which builds on a Unix core.
36
Benjamin Peterson68dbebc2009-12-31 03:30:26 +000037* An "Availability: Unix" note means that this function is commonly found on
38 Unix systems. It does not make any claims about its existence on a specific
39 operating system.
40
41* If not separately noted, all functions that claim "Availability: Unix" are
42 supported on Mac OS X, which builds on a Unix core.
43
Georg Brandlc575c902008-09-13 17:46:05 +000044.. note::
45
Christian Heimesa62da1d2008-01-12 19:39:10 +000046 All functions in this module raise :exc:`OSError` in the case of invalid or
47 inaccessible file names and paths, or other arguments that have the correct
48 type, but are not accepted by the operating system.
Georg Brandl116aa622007-08-15 14:28:22 +000049
Georg Brandl116aa622007-08-15 14:28:22 +000050.. exception:: error
51
Christian Heimesa62da1d2008-01-12 19:39:10 +000052 An alias for the built-in :exc:`OSError` exception.
Georg Brandl116aa622007-08-15 14:28:22 +000053
54
55.. data:: name
56
Benjamin Peterson68dbebc2009-12-31 03:30:26 +000057 The name of the operating system dependent module imported. The following
58 names have currently been registered: ``'posix'``, ``'nt'``, ``'mac'``,
59 ``'os2'``, ``'ce'``, ``'java'``.
Georg Brandl116aa622007-08-15 14:28:22 +000060
61
Martin v. Löwis011e8422009-05-05 04:43:17 +000062.. _os-filenames:
63
64File Names, Command Line Arguments, and Environment Variables
65-------------------------------------------------------------
66
67In Python, file names, command line arguments, and environment
68variables are represented using the string type. On some systems,
69decoding these strings to and from bytes is necessary before passing
70them to the operating system. Python uses the file system encoding to
71perform this conversion (see :func:`sys.getfilesystemencoding`).
72
73.. versionchanged:: 3.1
74 On some systems, conversion using the file system encoding may
Martin v. Löwis43c57782009-05-10 08:15:24 +000075 fail. In this case, Python uses the ``surrogateescape`` encoding
76 error handler, which means that undecodable bytes are replaced by a
Martin v. Löwis011e8422009-05-05 04:43:17 +000077 Unicode character U+DCxx on decoding, and these are again
78 translated to the original byte on encoding.
79
80
81The file system encoding must guarantee to successfully decode all
82bytes below 128. If the file system encoding fails to provide this
83guarantee, API functions may raise UnicodeErrors.
84
85
Georg Brandl116aa622007-08-15 14:28:22 +000086.. _os-procinfo:
87
88Process Parameters
89------------------
90
91These functions and data items provide information and operate on the current
92process and user.
93
94
95.. data:: environ
96
97 A mapping object representing the string environment. For example,
98 ``environ['HOME']`` is the pathname of your home directory (on some platforms),
99 and is equivalent to ``getenv("HOME")`` in C.
100
101 This mapping is captured the first time the :mod:`os` module is imported,
102 typically during Python startup as part of processing :file:`site.py`. Changes
103 to the environment made after this time are not reflected in ``os.environ``,
104 except for changes made by modifying ``os.environ`` directly.
105
106 If the platform supports the :func:`putenv` function, this mapping may be used
107 to modify the environment as well as query the environment. :func:`putenv` will
108 be called automatically when the mapping is modified.
109
110 .. note::
111
112 Calling :func:`putenv` directly does not change ``os.environ``, so it's better
113 to modify ``os.environ``.
114
115 .. note::
116
Georg Brandlc575c902008-09-13 17:46:05 +0000117 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
118 cause memory leaks. Refer to the system documentation for
119 :cfunc:`putenv`.
Georg Brandl116aa622007-08-15 14:28:22 +0000120
121 If :func:`putenv` is not provided, a modified copy of this mapping may be
122 passed to the appropriate process-creation functions to cause child processes
123 to use a modified environment.
124
Georg Brandl9afde1c2007-11-01 20:32:30 +0000125 If the platform supports the :func:`unsetenv` function, you can delete items in
Georg Brandl116aa622007-08-15 14:28:22 +0000126 this mapping to unset environment variables. :func:`unsetenv` will be called
Georg Brandl9afde1c2007-11-01 20:32:30 +0000127 automatically when an item is deleted from ``os.environ``, and when
128 one of the :meth:`pop` or :meth:`clear` methods is called.
129
Georg Brandl116aa622007-08-15 14:28:22 +0000130
131.. function:: chdir(path)
132 fchdir(fd)
133 getcwd()
134 :noindex:
135
136 These functions are described in :ref:`os-file-dir`.
137
138
139.. function:: ctermid()
140
141 Return the filename corresponding to the controlling terminal of the process.
142 Availability: Unix.
143
144
145.. function:: getegid()
146
147 Return the effective group id of the current process. This corresponds to the
Christian Heimesfaf2f632008-01-06 16:59:19 +0000148 "set id" bit on the file being executed in the current process. Availability:
Georg Brandl116aa622007-08-15 14:28:22 +0000149 Unix.
150
151
152.. function:: geteuid()
153
154 .. index:: single: user; effective id
155
Christian Heimesfaf2f632008-01-06 16:59:19 +0000156 Return the current process's effective user id. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000157
158
159.. function:: getgid()
160
161 .. index:: single: process; group
162
163 Return the real group id of the current process. Availability: Unix.
164
165
166.. function:: getgroups()
167
168 Return list of supplemental group ids associated with the current process.
169 Availability: Unix.
170
171
172.. function:: getlogin()
173
174 Return the name of the user logged in on the controlling terminal of the
175 process. For most purposes, it is more useful to use the environment variable
176 :envvar:`LOGNAME` to find out who the user is, or
177 ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the currently
Christian Heimesfaf2f632008-01-06 16:59:19 +0000178 effective user id. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000179
180
181.. function:: getpgid(pid)
182
183 Return the process group id of the process with process id *pid*. If *pid* is 0,
184 the process group id of the current process is returned. Availability: Unix.
185
Georg Brandl116aa622007-08-15 14:28:22 +0000186
187.. function:: getpgrp()
188
189 .. index:: single: process; group
190
191 Return the id of the current process group. Availability: Unix.
192
193
194.. function:: getpid()
195
196 .. index:: single: process; id
197
198 Return the current process id. Availability: Unix, Windows.
199
200
201.. function:: getppid()
202
203 .. index:: single: process; id of parent
204
205 Return the parent's process id. Availability: Unix.
206
207
208.. function:: getuid()
209
210 .. index:: single: user; id
211
Christian Heimesfaf2f632008-01-06 16:59:19 +0000212 Return the current process's user id. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000213
214
215.. function:: getenv(varname[, value])
216
217 Return the value of the environment variable *varname* if it exists, or *value*
218 if it doesn't. *value* defaults to ``None``. Availability: most flavors of
219 Unix, Windows.
220
221
222.. function:: putenv(varname, value)
223
224 .. index:: single: environment variables; setting
225
226 Set the environment variable named *varname* to the string *value*. Such
227 changes to the environment affect subprocesses started with :func:`os.system`,
228 :func:`popen` or :func:`fork` and :func:`execv`. Availability: most flavors of
229 Unix, Windows.
230
231 .. note::
232
Georg Brandlc575c902008-09-13 17:46:05 +0000233 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
234 cause memory leaks. Refer to the system documentation for putenv.
Georg Brandl116aa622007-08-15 14:28:22 +0000235
236 When :func:`putenv` is supported, assignments to items in ``os.environ`` are
237 automatically translated into corresponding calls to :func:`putenv`; however,
238 calls to :func:`putenv` don't update ``os.environ``, so it is actually
239 preferable to assign to items of ``os.environ``.
240
241
242.. function:: setegid(egid)
243
244 Set the current process's effective group id. Availability: Unix.
245
246
247.. function:: seteuid(euid)
248
249 Set the current process's effective user id. Availability: Unix.
250
251
252.. function:: setgid(gid)
253
254 Set the current process' group id. Availability: Unix.
255
256
257.. function:: setgroups(groups)
258
259 Set the list of supplemental group ids associated with the current process to
260 *groups*. *groups* must be a sequence, and each element must be an integer
Christian Heimesfaf2f632008-01-06 16:59:19 +0000261 identifying a group. This operation is typically available only to the superuser.
Georg Brandl116aa622007-08-15 14:28:22 +0000262 Availability: Unix.
263
Georg Brandl116aa622007-08-15 14:28:22 +0000264
265.. function:: setpgrp()
266
Christian Heimesfaf2f632008-01-06 16:59:19 +0000267 Call the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on
Georg Brandl116aa622007-08-15 14:28:22 +0000268 which version is implemented (if any). See the Unix manual for the semantics.
269 Availability: Unix.
270
271
272.. function:: setpgid(pid, pgrp)
273
Christian Heimesfaf2f632008-01-06 16:59:19 +0000274 Call the system call :cfunc:`setpgid` to set the process group id of the
Georg Brandl116aa622007-08-15 14:28:22 +0000275 process with id *pid* to the process group with id *pgrp*. See the Unix manual
276 for the semantics. Availability: Unix.
277
278
279.. function:: setreuid(ruid, euid)
280
281 Set the current process's real and effective user ids. Availability: Unix.
282
283
284.. function:: setregid(rgid, egid)
285
286 Set the current process's real and effective group ids. Availability: Unix.
287
288
289.. function:: getsid(pid)
290
Christian Heimesfaf2f632008-01-06 16:59:19 +0000291 Call the system call :cfunc:`getsid`. See the Unix manual for the semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000292 Availability: Unix.
293
Georg Brandl116aa622007-08-15 14:28:22 +0000294
295.. function:: setsid()
296
Christian Heimesfaf2f632008-01-06 16:59:19 +0000297 Call the system call :cfunc:`setsid`. See the Unix manual for the semantics.
Georg Brandl116aa622007-08-15 14:28:22 +0000298 Availability: Unix.
299
300
301.. function:: setuid(uid)
302
303 .. index:: single: user; id, setting
304
Christian Heimesfaf2f632008-01-06 16:59:19 +0000305 Set the current process's user id. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000306
Georg Brandl116aa622007-08-15 14:28:22 +0000307
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000308.. placed in this section since it relates to errno.... a little weak
Georg Brandl116aa622007-08-15 14:28:22 +0000309.. function:: strerror(code)
310
311 Return the error message corresponding to the error code in *code*.
Alexandre Vassalotti8ae3e052008-05-16 00:41:41 +0000312 On platforms where :cfunc:`strerror` returns ``NULL`` when given an unknown
313 error number, :exc:`ValueError` is raised. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000314
315
316.. function:: umask(mask)
317
Christian Heimesfaf2f632008-01-06 16:59:19 +0000318 Set the current numeric umask and return the previous umask. Availability:
Georg Brandl116aa622007-08-15 14:28:22 +0000319 Unix, Windows.
320
321
322.. function:: uname()
323
324 .. index::
325 single: gethostname() (in module socket)
326 single: gethostbyaddr() (in module socket)
327
328 Return a 5-tuple containing information identifying the current operating
329 system. The tuple contains 5 strings: ``(sysname, nodename, release, version,
330 machine)``. Some systems truncate the nodename to 8 characters or to the
331 leading component; a better way to get the hostname is
332 :func:`socket.gethostname` or even
333 ``socket.gethostbyaddr(socket.gethostname())``. Availability: recent flavors of
334 Unix.
335
336
337.. function:: unsetenv(varname)
338
339 .. index:: single: environment variables; deleting
340
341 Unset (delete) the environment variable named *varname*. Such changes to the
342 environment affect subprocesses started with :func:`os.system`, :func:`popen` or
343 :func:`fork` and :func:`execv`. Availability: most flavors of Unix, Windows.
344
345 When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is
346 automatically translated into a corresponding call to :func:`unsetenv`; however,
347 calls to :func:`unsetenv` don't update ``os.environ``, so it is actually
348 preferable to delete items of ``os.environ``.
349
350
351.. _os-newstreams:
352
353File Object Creation
354--------------------
355
356These functions create new file objects. (See also :func:`open`.)
357
358
359.. function:: fdopen(fd[, mode[, bufsize]])
360
361 .. index:: single: I/O control; buffering
362
363 Return an open file object connected to the file descriptor *fd*. The *mode*
364 and *bufsize* arguments have the same meaning as the corresponding arguments to
Georg Brandlc575c902008-09-13 17:46:05 +0000365 the built-in :func:`open` function. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000366
Georg Brandl55ac8f02007-09-01 13:51:09 +0000367 When specified, the *mode* argument must start with one of the letters
368 ``'r'``, ``'w'``, or ``'a'``, otherwise a :exc:`ValueError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000369
Georg Brandl55ac8f02007-09-01 13:51:09 +0000370 On Unix, when the *mode* argument starts with ``'a'``, the *O_APPEND* flag is
371 set on the file descriptor (which the :cfunc:`fdopen` implementation already
372 does on most platforms).
Georg Brandl116aa622007-08-15 14:28:22 +0000373
374
Georg Brandl116aa622007-08-15 14:28:22 +0000375.. _os-fd-ops:
376
377File Descriptor Operations
378--------------------------
379
380These functions operate on I/O streams referenced using file descriptors.
381
382File descriptors are small integers corresponding to a file that has been opened
383by the current process. For example, standard input is usually file descriptor
3840, standard output is 1, and standard error is 2. Further files opened by a
385process will then be assigned 3, 4, 5, and so forth. The name "file descriptor"
386is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
387by file descriptors.
388
389
390.. function:: close(fd)
391
Georg Brandlc575c902008-09-13 17:46:05 +0000392 Close file descriptor *fd*. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000393
394 .. note::
395
396 This function is intended for low-level I/O and must be applied to a file
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000397 descriptor as returned by :func:`os.open` or :func:`pipe`. To close a "file
Georg Brandl116aa622007-08-15 14:28:22 +0000398 object" returned by the built-in function :func:`open` or by :func:`popen` or
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000399 :func:`fdopen`, use its :meth:`~file.close` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000400
401
Christian Heimesfdab48e2008-01-20 09:06:41 +0000402.. function:: closerange(fd_low, fd_high)
403
404 Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive),
Georg Brandlc575c902008-09-13 17:46:05 +0000405 ignoring errors. Availability: Unix, Windows. Equivalent to::
Christian Heimesfdab48e2008-01-20 09:06:41 +0000406
Georg Brandl7baf6252009-09-01 08:13:16 +0000407 for fd in range(fd_low, fd_high):
Christian Heimesfdab48e2008-01-20 09:06:41 +0000408 try:
409 os.close(fd)
410 except OSError:
411 pass
412
Christian Heimesfdab48e2008-01-20 09:06:41 +0000413
Georg Brandl81f11302007-12-21 08:45:42 +0000414.. function:: device_encoding(fd)
415
416 Return a string describing the encoding of the device associated with *fd*
417 if it is connected to a terminal; else return :const:`None`.
418
419
Georg Brandl116aa622007-08-15 14:28:22 +0000420.. function:: dup(fd)
421
Georg Brandlc575c902008-09-13 17:46:05 +0000422 Return a duplicate of file descriptor *fd*. Availability: Unix,
Georg Brandl116aa622007-08-15 14:28:22 +0000423 Windows.
424
425
426.. function:: dup2(fd, fd2)
427
428 Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary.
Georg Brandlc575c902008-09-13 17:46:05 +0000429 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000430
431
Christian Heimes4e30a842007-11-30 22:12:06 +0000432.. function:: fchmod(fd, mode)
433
434 Change the mode of the file given by *fd* to the numeric *mode*. See the docs
435 for :func:`chmod` for possible values of *mode*. Availability: Unix.
436
437
438.. function:: fchown(fd, uid, gid)
439
440 Change the owner and group id of the file given by *fd* to the numeric *uid*
441 and *gid*. To leave one of the ids unchanged, set it to -1.
442 Availability: Unix.
443
444
Georg Brandl116aa622007-08-15 14:28:22 +0000445.. function:: fdatasync(fd)
446
447 Force write of file with filedescriptor *fd* to disk. Does not force update of
448 metadata. Availability: Unix.
449
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000450 .. note::
451 This function is not available on MacOS.
452
Georg Brandl116aa622007-08-15 14:28:22 +0000453
454.. function:: fpathconf(fd, name)
455
456 Return system configuration information relevant to an open file. *name*
457 specifies the configuration value to retrieve; it may be a string which is the
458 name of a defined system value; these names are specified in a number of
459 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
460 additional names as well. The names known to the host operating system are
461 given in the ``pathconf_names`` dictionary. For configuration variables not
462 included in that mapping, passing an integer for *name* is also accepted.
Georg Brandlc575c902008-09-13 17:46:05 +0000463 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000464
465 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
466 specific value for *name* is not supported by the host system, even if it is
467 included in ``pathconf_names``, an :exc:`OSError` is raised with
468 :const:`errno.EINVAL` for the error number.
469
470
471.. function:: fstat(fd)
472
473 Return status for file descriptor *fd*, like :func:`stat`. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +0000474 Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000475
476
477.. function:: fstatvfs(fd)
478
479 Return information about the filesystem containing the file associated with file
480 descriptor *fd*, like :func:`statvfs`. Availability: Unix.
481
482
483.. function:: fsync(fd)
484
485 Force write of file with filedescriptor *fd* to disk. On Unix, this calls the
486 native :cfunc:`fsync` function; on Windows, the MS :cfunc:`_commit` function.
487
488 If you're starting with a Python file object *f*, first do ``f.flush()``, and
489 then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated
Georg Brandlc575c902008-09-13 17:46:05 +0000490 with *f* are written to disk. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000491
492
493.. function:: ftruncate(fd, length)
494
495 Truncate the file corresponding to file descriptor *fd*, so that it is at most
Georg Brandlc575c902008-09-13 17:46:05 +0000496 *length* bytes in size. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000497
498
499.. function:: isatty(fd)
500
501 Return ``True`` if the file descriptor *fd* is open and connected to a
Georg Brandlc575c902008-09-13 17:46:05 +0000502 tty(-like) device, else ``False``. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000503
504
505.. function:: lseek(fd, pos, how)
506
Christian Heimesfaf2f632008-01-06 16:59:19 +0000507 Set the current position of file descriptor *fd* to position *pos*, modified
508 by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the
509 beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the
510 current position; :const:`os.SEEK_END` or ``2`` to set it relative to the end of
Georg Brandlc575c902008-09-13 17:46:05 +0000511 the file. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000512
513
514.. function:: open(file, flags[, mode])
515
Georg Brandlf4a41232008-05-26 17:55:52 +0000516 Open the file *file* and set various flags according to *flags* and possibly
517 its mode according to *mode*. The default *mode* is ``0o777`` (octal), and
518 the current umask value is first masked out. Return the file descriptor for
Georg Brandlc575c902008-09-13 17:46:05 +0000519 the newly opened file. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000520
521 For a description of the flag and mode values, see the C run-time documentation;
522 flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
523 this module too (see below).
524
525 .. note::
526
Georg Brandlc5605df2009-08-13 08:26:44 +0000527 This function is intended for low-level I/O. For normal usage, use the
528 built-in function :func:`open`, which returns a "file object" with
529 :meth:`~file.read` and :meth:`~file.write` methods (and many more). To
530 wrap a file descriptor in a "file object", use :func:`fdopen`.
Georg Brandl116aa622007-08-15 14:28:22 +0000531
532
533.. function:: openpty()
534
535 .. index:: module: pty
536
537 Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master,
538 slave)`` for the pty and the tty, respectively. For a (slightly) more portable
Georg Brandlc575c902008-09-13 17:46:05 +0000539 approach, use the :mod:`pty` module. Availability: some flavors of
Georg Brandl116aa622007-08-15 14:28:22 +0000540 Unix.
541
542
543.. function:: pipe()
544
545 Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading
Georg Brandlc575c902008-09-13 17:46:05 +0000546 and writing, respectively. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000547
548
549.. function:: read(fd, n)
550
Georg Brandlc5605df2009-08-13 08:26:44 +0000551 Read at most *n* bytes from file descriptor *fd*. Return a bytestring containing the
Georg Brandl116aa622007-08-15 14:28:22 +0000552 bytes read. If the end of the file referred to by *fd* has been reached, an
Georg Brandlc5605df2009-08-13 08:26:44 +0000553 empty bytes object is returned. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000554
555 .. note::
556
557 This function is intended for low-level I/O and must be applied to a file
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000558 descriptor as returned by :func:`os.open` or :func:`pipe`. To read a "file object"
Georg Brandl116aa622007-08-15 14:28:22 +0000559 returned by the built-in function :func:`open` or by :func:`popen` or
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000560 :func:`fdopen`, or :data:`sys.stdin`, use its :meth:`~file.read` or
561 :meth:`~file.readline` methods.
Georg Brandl116aa622007-08-15 14:28:22 +0000562
563
564.. function:: tcgetpgrp(fd)
565
566 Return the process group associated with the terminal given by *fd* (an open
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000567 file descriptor as returned by :func:`os.open`). Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000568
569
570.. function:: tcsetpgrp(fd, pg)
571
572 Set the process group associated with the terminal given by *fd* (an open file
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000573 descriptor as returned by :func:`os.open`) to *pg*. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000574
575
576.. function:: ttyname(fd)
577
578 Return a string which specifies the terminal device associated with
Georg Brandl9afde1c2007-11-01 20:32:30 +0000579 file descriptor *fd*. If *fd* is not associated with a terminal device, an
Georg Brandlc575c902008-09-13 17:46:05 +0000580 exception is raised. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000581
582
583.. function:: write(fd, str)
584
Georg Brandlc5605df2009-08-13 08:26:44 +0000585 Write the bytestring in *str* to file descriptor *fd*. Return the number of
586 bytes actually written. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000587
588 .. note::
589
590 This function is intended for low-level I/O and must be applied to a file
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000591 descriptor as returned by :func:`os.open` or :func:`pipe`. To write a "file
Georg Brandl116aa622007-08-15 14:28:22 +0000592 object" returned by the built-in function :func:`open` or by :func:`popen` or
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000593 :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its
594 :meth:`~file.write` method.
Georg Brandl116aa622007-08-15 14:28:22 +0000595
Georg Brandlaf265f42008-12-07 15:06:20 +0000596The following constants are options for the *flags* parameter to the
Benjamin Petersonfa0d7032009-06-01 22:42:33 +0000597:func:`~os.open` function. They can be combined using the bitwise OR operator
Georg Brandlaf265f42008-12-07 15:06:20 +0000598``|``. Some of them are not available on all platforms. For descriptions of
599their availability and use, consult the :manpage:`open(2)` manual page on Unix
Doug Hellmann14214262009-09-21 12:16:43 +0000600or `the MSDN <http://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>`_ on Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000601
602
603.. data:: O_RDONLY
604 O_WRONLY
605 O_RDWR
606 O_APPEND
607 O_CREAT
608 O_EXCL
609 O_TRUNC
610
Georg Brandlaf265f42008-12-07 15:06:20 +0000611 These constants are available on Unix and Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000612
613
614.. data:: O_DSYNC
615 O_RSYNC
616 O_SYNC
617 O_NDELAY
618 O_NONBLOCK
619 O_NOCTTY
620 O_SHLOCK
621 O_EXLOCK
622
Georg Brandlaf265f42008-12-07 15:06:20 +0000623 These constants are only available on Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000624
625
626.. data:: O_BINARY
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000627 O_NOINHERIT
Georg Brandl116aa622007-08-15 14:28:22 +0000628 O_SHORT_LIVED
629 O_TEMPORARY
630 O_RANDOM
631 O_SEQUENTIAL
632 O_TEXT
633
Georg Brandlaf265f42008-12-07 15:06:20 +0000634 These constants are only available on Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000635
636
Alexandre Vassalottibee32532008-05-16 18:15:12 +0000637.. data:: O_ASYNC
638 O_DIRECT
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000639 O_DIRECTORY
640 O_NOFOLLOW
641 O_NOATIME
642
Georg Brandlaf265f42008-12-07 15:06:20 +0000643 These constants are GNU extensions and not present if they are not defined by
644 the C library.
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000645
646
Georg Brandl116aa622007-08-15 14:28:22 +0000647.. data:: SEEK_SET
648 SEEK_CUR
649 SEEK_END
650
651 Parameters to the :func:`lseek` function. Their values are 0, 1, and 2,
Georg Brandlc575c902008-09-13 17:46:05 +0000652 respectively. Availability: Windows, Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000653
Georg Brandl116aa622007-08-15 14:28:22 +0000654
655.. _os-file-dir:
656
657Files and Directories
658---------------------
659
Georg Brandl116aa622007-08-15 14:28:22 +0000660.. function:: access(path, mode)
661
662 Use the real uid/gid to test for access to *path*. Note that most operations
663 will use the effective uid/gid, therefore this routine can be used in a
664 suid/sgid environment to test if the invoking user has the specified access to
665 *path*. *mode* should be :const:`F_OK` to test the existence of *path*, or it
666 can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and
667 :const:`X_OK` to test permissions. Return :const:`True` if access is allowed,
668 :const:`False` if not. See the Unix man page :manpage:`access(2)` for more
Georg Brandlc575c902008-09-13 17:46:05 +0000669 information. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000670
671 .. note::
672
Georg Brandlc5605df2009-08-13 08:26:44 +0000673 Using :func:`access` to check if a user is authorized to e.g. open a file
674 before actually doing so using :func:`open` creates a security hole,
675 because the user might exploit the short time interval between checking
676 and opening the file to manipulate it.
Georg Brandl116aa622007-08-15 14:28:22 +0000677
678 .. note::
679
680 I/O operations may fail even when :func:`access` indicates that they would
681 succeed, particularly for operations on network filesystems which may have
682 permissions semantics beyond the usual POSIX permission-bit model.
683
684
685.. data:: F_OK
686
687 Value to pass as the *mode* parameter of :func:`access` to test the existence of
688 *path*.
689
690
691.. data:: R_OK
692
693 Value to include in the *mode* parameter of :func:`access` to test the
694 readability of *path*.
695
696
697.. data:: W_OK
698
699 Value to include in the *mode* parameter of :func:`access` to test the
700 writability of *path*.
701
702
703.. data:: X_OK
704
705 Value to include in the *mode* parameter of :func:`access` to determine if
706 *path* can be executed.
707
708
709.. function:: chdir(path)
710
711 .. index:: single: directory; changing
712
Georg Brandlc575c902008-09-13 17:46:05 +0000713 Change the current working directory to *path*. Availability: Unix,
Georg Brandl116aa622007-08-15 14:28:22 +0000714 Windows.
715
716
717.. function:: fchdir(fd)
718
719 Change the current working directory to the directory represented by the file
720 descriptor *fd*. The descriptor must refer to an opened directory, not an open
721 file. Availability: Unix.
722
Georg Brandl116aa622007-08-15 14:28:22 +0000723
724.. function:: getcwd()
725
Martin v. Löwis011e8422009-05-05 04:43:17 +0000726 Return a string representing the current working directory.
727 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000728
Martin v. Löwisa731b992008-10-07 06:36:31 +0000729.. function:: getcwdb()
Georg Brandl116aa622007-08-15 14:28:22 +0000730
Georg Brandl76e55382008-10-08 16:34:57 +0000731 Return a bytestring representing the current working directory.
Georg Brandlc575c902008-09-13 17:46:05 +0000732 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000733
Georg Brandl116aa622007-08-15 14:28:22 +0000734
735.. function:: chflags(path, flags)
736
737 Set the flags of *path* to the numeric *flags*. *flags* may take a combination
738 (bitwise OR) of the following values (as defined in the :mod:`stat` module):
739
740 * ``UF_NODUMP``
741 * ``UF_IMMUTABLE``
742 * ``UF_APPEND``
743 * ``UF_OPAQUE``
744 * ``UF_NOUNLINK``
745 * ``SF_ARCHIVED``
746 * ``SF_IMMUTABLE``
747 * ``SF_APPEND``
748 * ``SF_NOUNLINK``
749 * ``SF_SNAPSHOT``
750
Georg Brandlc575c902008-09-13 17:46:05 +0000751 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000752
Georg Brandl116aa622007-08-15 14:28:22 +0000753
754.. function:: chroot(path)
755
756 Change the root directory of the current process to *path*. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +0000757 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000758
Georg Brandl116aa622007-08-15 14:28:22 +0000759
760.. function:: chmod(path, mode)
761
762 Change the mode of *path* to the numeric *mode*. *mode* may take one of the
Christian Heimesfaf2f632008-01-06 16:59:19 +0000763 following values (as defined in the :mod:`stat` module) or bitwise ORed
Georg Brandl116aa622007-08-15 14:28:22 +0000764 combinations of them:
765
R. David Murrayba426142009-07-21 14:29:59 +0000766 * :data:`stat.S_ISUID`
767 * :data:`stat.S_ISGID`
768 * :data:`stat.S_ENFMT`
769 * :data:`stat.S_ISVTX`
770 * :data:`stat.S_IREAD`
771 * :data:`stat.S_IWRITE`
772 * :data:`stat.S_IEXEC`
773 * :data:`stat.S_IRWXU`
774 * :data:`stat.S_IRUSR`
775 * :data:`stat.S_IWUSR`
776 * :data:`stat.S_IXUSR`
777 * :data:`stat.S_IRWXG`
778 * :data:`stat.S_IRGRP`
779 * :data:`stat.S_IWGRP`
780 * :data:`stat.S_IXGRP`
781 * :data:`stat.S_IRWXO`
782 * :data:`stat.S_IROTH`
783 * :data:`stat.S_IWOTH`
784 * :data:`stat.S_IXOTH`
Georg Brandl116aa622007-08-15 14:28:22 +0000785
Georg Brandlc575c902008-09-13 17:46:05 +0000786 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000787
788 .. note::
789
790 Although Windows supports :func:`chmod`, you can only set the file's read-only
791 flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD``
792 constants or a corresponding integer value). All other bits are
793 ignored.
794
795
796.. function:: chown(path, uid, gid)
797
798 Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave
Georg Brandlc575c902008-09-13 17:46:05 +0000799 one of the ids unchanged, set it to -1. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000800
801
802.. function:: lchflags(path, flags)
803
804 Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not
805 follow symbolic links. Availability: Unix.
806
Georg Brandl116aa622007-08-15 14:28:22 +0000807
Christian Heimes93852662007-12-01 12:22:32 +0000808.. function:: lchmod(path, mode)
809
810 Change the mode of *path* to the numeric *mode*. If path is a symlink, this
811 affects the symlink rather than the target. See the docs for :func:`chmod`
812 for possible values of *mode*. Availability: Unix.
813
Christian Heimes93852662007-12-01 12:22:32 +0000814
Georg Brandl116aa622007-08-15 14:28:22 +0000815.. function:: lchown(path, uid, gid)
816
Christian Heimesfaf2f632008-01-06 16:59:19 +0000817 Change the owner and group id of *path* to the numeric *uid* and *gid*. This
Georg Brandlc575c902008-09-13 17:46:05 +0000818 function will not follow symbolic links. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000819
Georg Brandl116aa622007-08-15 14:28:22 +0000820
Benjamin Peterson5879d412009-03-30 14:51:56 +0000821.. function:: link(source, link_name)
Georg Brandl116aa622007-08-15 14:28:22 +0000822
Benjamin Peterson5879d412009-03-30 14:51:56 +0000823 Create a hard link pointing to *source* named *link_name*. Availability:
824 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000825
826
827.. function:: listdir(path)
828
Benjamin Peterson4469d0c2008-11-30 22:46:23 +0000829 Return a list containing the names of the entries in the directory given by
830 *path*. The list is in arbitrary order. It does not include the special
831 entries ``'.'`` and ``'..'`` even if they are present in the directory.
832 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000833
Martin v. Löwis011e8422009-05-05 04:43:17 +0000834 This function can be called with a bytes or string argument, and returns
835 filenames of the same datatype.
Georg Brandl116aa622007-08-15 14:28:22 +0000836
837
838.. function:: lstat(path)
839
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000840 Like :func:`stat`, but do not follow symbolic links. This is an alias for
841 :func:`stat` on platforms that do not support symbolic links, such as
842 Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000843
844
845.. function:: mkfifo(path[, mode])
846
Georg Brandlf4a41232008-05-26 17:55:52 +0000847 Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The
848 default *mode* is ``0o666`` (octal). The current umask value is first masked
Georg Brandlc575c902008-09-13 17:46:05 +0000849 out from the mode. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000850
851 FIFOs are pipes that can be accessed like regular files. FIFOs exist until they
852 are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
853 rendezvous between "client" and "server" type processes: the server opens the
854 FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo`
855 doesn't open the FIFO --- it just creates the rendezvous point.
856
857
Georg Brandlf4a41232008-05-26 17:55:52 +0000858.. function:: mknod(filename[, mode=0o600, device])
Georg Brandl116aa622007-08-15 14:28:22 +0000859
860 Create a filesystem node (file, device special file or named pipe) named
861 *filename*. *mode* specifies both the permissions to use and the type of node to
862 be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
863 ``stat.S_IFCHR``, ``stat.S_IFBLK``,
864 and ``stat.S_IFIFO`` (those constants are available in :mod:`stat`).
865 For ``stat.S_IFCHR`` and
866 ``stat.S_IFBLK``, *device* defines the newly created device special file (probably using
867 :func:`os.makedev`), otherwise it is ignored.
868
Georg Brandl116aa622007-08-15 14:28:22 +0000869
870.. function:: major(device)
871
Christian Heimesfaf2f632008-01-06 16:59:19 +0000872 Extract the device major number from a raw device number (usually the
Georg Brandl116aa622007-08-15 14:28:22 +0000873 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
874
Georg Brandl116aa622007-08-15 14:28:22 +0000875
876.. function:: minor(device)
877
Christian Heimesfaf2f632008-01-06 16:59:19 +0000878 Extract the device minor number from a raw device number (usually the
Georg Brandl116aa622007-08-15 14:28:22 +0000879 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
880
Georg Brandl116aa622007-08-15 14:28:22 +0000881
882.. function:: makedev(major, minor)
883
Christian Heimesfaf2f632008-01-06 16:59:19 +0000884 Compose a raw device number from the major and minor device numbers.
Georg Brandl116aa622007-08-15 14:28:22 +0000885
Georg Brandl116aa622007-08-15 14:28:22 +0000886
887.. function:: mkdir(path[, mode])
888
Georg Brandlf4a41232008-05-26 17:55:52 +0000889 Create a directory named *path* with numeric mode *mode*. The default *mode*
890 is ``0o777`` (octal). On some systems, *mode* is ignored. Where it is used,
Georg Brandlc575c902008-09-13 17:46:05 +0000891 the current umask value is first masked out. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000892
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000893 It is also possible to create temporary directories; see the
894 :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
895
Georg Brandl116aa622007-08-15 14:28:22 +0000896
897.. function:: makedirs(path[, mode])
898
899 .. index::
900 single: directory; creating
901 single: UNC paths; and os.makedirs()
902
903 Recursive directory creation function. Like :func:`mkdir`, but makes all
Georg Brandlf4a41232008-05-26 17:55:52 +0000904 intermediate-level directories needed to contain the leaf directory. Throws
905 an :exc:`error` exception if the leaf directory already exists or cannot be
906 created. The default *mode* is ``0o777`` (octal). On some systems, *mode*
907 is ignored. Where it is used, the current umask value is first masked out.
Georg Brandl116aa622007-08-15 14:28:22 +0000908
909 .. note::
910
911 :func:`makedirs` will become confused if the path elements to create include
Christian Heimesfaf2f632008-01-06 16:59:19 +0000912 :data:`os.pardir`.
Georg Brandl116aa622007-08-15 14:28:22 +0000913
Georg Brandl55ac8f02007-09-01 13:51:09 +0000914 This function handles UNC paths correctly.
Georg Brandl116aa622007-08-15 14:28:22 +0000915
916
917.. function:: pathconf(path, name)
918
919 Return system configuration information relevant to a named file. *name*
920 specifies the configuration value to retrieve; it may be a string which is the
921 name of a defined system value; these names are specified in a number of
922 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
923 additional names as well. The names known to the host operating system are
924 given in the ``pathconf_names`` dictionary. For configuration variables not
925 included in that mapping, passing an integer for *name* is also accepted.
Georg Brandlc575c902008-09-13 17:46:05 +0000926 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000927
928 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
929 specific value for *name* is not supported by the host system, even if it is
930 included in ``pathconf_names``, an :exc:`OSError` is raised with
931 :const:`errno.EINVAL` for the error number.
932
933
934.. data:: pathconf_names
935
936 Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
937 the integer values defined for those names by the host operating system. This
938 can be used to determine the set of names known to the system. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +0000939 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000940
941
942.. function:: readlink(path)
943
944 Return a string representing the path to which the symbolic link points. The
945 result may be either an absolute or relative pathname; if it is relative, it may
946 be converted to an absolute pathname using ``os.path.join(os.path.dirname(path),
947 result)``.
948
Georg Brandl76e55382008-10-08 16:34:57 +0000949 If the *path* is a string object, the result will also be a string object,
950 and the call may raise an UnicodeDecodeError. If the *path* is a bytes
951 object, the result will be a bytes object.
Georg Brandl116aa622007-08-15 14:28:22 +0000952
Georg Brandlc575c902008-09-13 17:46:05 +0000953 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +0000954
955
956.. function:: remove(path)
957
Georg Brandl7baf6252009-09-01 08:13:16 +0000958 Remove (delete) the file *path*. If *path* is a directory, :exc:`OSError` is
959 raised; see :func:`rmdir` below to remove a directory. This is identical to
960 the :func:`unlink` function documented below. On Windows, attempting to
961 remove a file that is in use causes an exception to be raised; on Unix, the
962 directory entry is removed but the storage allocated to the file is not made
963 available until the original file is no longer in use. Availability: Unix,
Georg Brandl116aa622007-08-15 14:28:22 +0000964 Windows.
965
966
967.. function:: removedirs(path)
968
969 .. index:: single: directory; deleting
970
Christian Heimesfaf2f632008-01-06 16:59:19 +0000971 Remove directories recursively. Works like :func:`rmdir` except that, if the
Georg Brandl116aa622007-08-15 14:28:22 +0000972 leaf directory is successfully removed, :func:`removedirs` tries to
973 successively remove every parent directory mentioned in *path* until an error
974 is raised (which is ignored, because it generally means that a parent directory
975 is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
976 the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
977 they are empty. Raises :exc:`OSError` if the leaf directory could not be
978 successfully removed.
979
Georg Brandl116aa622007-08-15 14:28:22 +0000980
981.. function:: rename(src, dst)
982
983 Rename the file or directory *src* to *dst*. If *dst* is a directory,
984 :exc:`OSError` will be raised. On Unix, if *dst* exists and is a file, it will
Christian Heimesfaf2f632008-01-06 16:59:19 +0000985 be replaced silently if the user has permission. The operation may fail on some
Georg Brandl116aa622007-08-15 14:28:22 +0000986 Unix flavors if *src* and *dst* are on different filesystems. If successful,
987 the renaming will be an atomic operation (this is a POSIX requirement). On
988 Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a
989 file; there may be no way to implement an atomic rename when *dst* names an
Georg Brandlc575c902008-09-13 17:46:05 +0000990 existing file. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000991
992
993.. function:: renames(old, new)
994
995 Recursive directory or file renaming function. Works like :func:`rename`, except
996 creation of any intermediate directories needed to make the new pathname good is
997 attempted first. After the rename, directories corresponding to rightmost path
998 segments of the old name will be pruned away using :func:`removedirs`.
999
Georg Brandl116aa622007-08-15 14:28:22 +00001000 .. note::
1001
1002 This function can fail with the new directory structure made if you lack
1003 permissions needed to remove the leaf directory or file.
1004
1005
1006.. function:: rmdir(path)
1007
Georg Brandl7baf6252009-09-01 08:13:16 +00001008 Remove (delete) the directory *path*. Only works when the directory is
1009 empty, otherwise, :exc:`OSError` is raised. In order to remove whole
1010 directory trees, :func:`shutil.rmtree` can be used. Availability: Unix,
1011 Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001012
1013
1014.. function:: stat(path)
1015
1016 Perform a :cfunc:`stat` system call on the given path. The return value is an
1017 object whose attributes correspond to the members of the :ctype:`stat`
1018 structure, namely: :attr:`st_mode` (protection bits), :attr:`st_ino` (inode
1019 number), :attr:`st_dev` (device), :attr:`st_nlink` (number of hard links),
Christian Heimesfaf2f632008-01-06 16:59:19 +00001020 :attr:`st_uid` (user id of owner), :attr:`st_gid` (group id of owner),
Georg Brandl116aa622007-08-15 14:28:22 +00001021 :attr:`st_size` (size of file, in bytes), :attr:`st_atime` (time of most recent
1022 access), :attr:`st_mtime` (time of most recent content modification),
1023 :attr:`st_ctime` (platform dependent; time of most recent metadata change on
1024 Unix, or the time of creation on Windows)::
1025
1026 >>> import os
1027 >>> statinfo = os.stat('somefile.txt')
1028 >>> statinfo
1029 (33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
1030 >>> statinfo.st_size
1031 926L
1032 >>>
1033
Georg Brandl116aa622007-08-15 14:28:22 +00001034
1035 On some Unix systems (such as Linux), the following attributes may also be
1036 available: :attr:`st_blocks` (number of blocks allocated for file),
1037 :attr:`st_blksize` (filesystem blocksize), :attr:`st_rdev` (type of device if an
1038 inode device). :attr:`st_flags` (user defined flags for file).
1039
1040 On other Unix systems (such as FreeBSD), the following attributes may be
1041 available (but may be only filled out if root tries to use them): :attr:`st_gen`
1042 (file generation number), :attr:`st_birthtime` (time of file creation).
1043
1044 On Mac OS systems, the following attributes may also be available:
1045 :attr:`st_rsize`, :attr:`st_creator`, :attr:`st_type`.
1046
Georg Brandl116aa622007-08-15 14:28:22 +00001047 .. index:: module: stat
1048
1049 For backward compatibility, the return value of :func:`stat` is also accessible
1050 as a tuple of at least 10 integers giving the most important (and portable)
1051 members of the :ctype:`stat` structure, in the order :attr:`st_mode`,
1052 :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, :attr:`st_uid`,
1053 :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, :attr:`st_mtime`,
1054 :attr:`st_ctime`. More items may be added at the end by some implementations.
1055 The standard module :mod:`stat` defines functions and constants that are useful
1056 for extracting information from a :ctype:`stat` structure. (On Windows, some
1057 items are filled with dummy values.)
1058
1059 .. note::
1060
1061 The exact meaning and resolution of the :attr:`st_atime`, :attr:`st_mtime`, and
1062 :attr:`st_ctime` members depends on the operating system and the file system.
1063 For example, on Windows systems using the FAT or FAT32 file systems,
1064 :attr:`st_mtime` has 2-second resolution, and :attr:`st_atime` has only 1-day
1065 resolution. See your operating system documentation for details.
1066
Georg Brandlc575c902008-09-13 17:46:05 +00001067 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001068
Georg Brandl116aa622007-08-15 14:28:22 +00001069
1070.. function:: stat_float_times([newvalue])
1071
1072 Determine whether :class:`stat_result` represents time stamps as float objects.
1073 If *newvalue* is ``True``, future calls to :func:`stat` return floats, if it is
1074 ``False``, future calls return ints. If *newvalue* is omitted, return the
1075 current setting.
1076
1077 For compatibility with older Python versions, accessing :class:`stat_result` as
1078 a tuple always returns integers.
1079
Georg Brandl55ac8f02007-09-01 13:51:09 +00001080 Python now returns float values by default. Applications which do not work
1081 correctly with floating point time stamps can use this function to restore the
1082 old behaviour.
Georg Brandl116aa622007-08-15 14:28:22 +00001083
1084 The resolution of the timestamps (that is the smallest possible fraction)
1085 depends on the system. Some systems only support second resolution; on these
1086 systems, the fraction will always be zero.
1087
1088 It is recommended that this setting is only changed at program startup time in
1089 the *__main__* module; libraries should never change this setting. If an
1090 application uses a library that works incorrectly if floating point time stamps
1091 are processed, this application should turn the feature off until the library
1092 has been corrected.
1093
1094
1095.. function:: statvfs(path)
1096
1097 Perform a :cfunc:`statvfs` system call on the given path. The return value is
1098 an object whose attributes describe the filesystem on the given path, and
1099 correspond to the members of the :ctype:`statvfs` structure, namely:
1100 :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
1101 :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
1102 :attr:`f_flag`, :attr:`f_namemax`. Availability: Unix.
1103
Georg Brandl116aa622007-08-15 14:28:22 +00001104
Benjamin Peterson5879d412009-03-30 14:51:56 +00001105.. function:: symlink(source, link_name)
Georg Brandl116aa622007-08-15 14:28:22 +00001106
Benjamin Peterson5879d412009-03-30 14:51:56 +00001107 Create a symbolic link pointing to *source* named *link_name*. Availability:
1108 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001109
1110
Georg Brandl116aa622007-08-15 14:28:22 +00001111.. function:: unlink(path)
1112
Georg Brandl7baf6252009-09-01 08:13:16 +00001113 Remove (delete) the file *path*. This is the same function as
1114 :func:`remove`; the :func:`unlink` name is its traditional Unix
1115 name. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001116
1117
1118.. function:: utime(path, times)
1119
Benjamin Peterson4cd6a952008-08-17 20:23:46 +00001120 Set the access and modified times of the file specified by *path*. If *times*
1121 is ``None``, then the file's access and modified times are set to the current
1122 time. (The effect is similar to running the Unix program :program:`touch` on
1123 the path.) Otherwise, *times* must be a 2-tuple of numbers, of the form
1124 ``(atime, mtime)`` which is used to set the access and modified times,
1125 respectively. Whether a directory can be given for *path* depends on whether
1126 the operating system implements directories as files (for example, Windows
1127 does not). Note that the exact times you set here may not be returned by a
1128 subsequent :func:`stat` call, depending on the resolution with which your
1129 operating system records access and modification times; see :func:`stat`.
Georg Brandl116aa622007-08-15 14:28:22 +00001130
Georg Brandlc575c902008-09-13 17:46:05 +00001131 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001132
1133
1134.. function:: walk(top[, topdown=True [, onerror=None[, followlinks=False]]])
1135
1136 .. index::
1137 single: directory; walking
1138 single: directory; traversal
1139
Christian Heimesfaf2f632008-01-06 16:59:19 +00001140 Generate the file names in a directory tree by walking the tree
1141 either top-down or bottom-up. For each directory in the tree rooted at directory
Georg Brandl116aa622007-08-15 14:28:22 +00001142 *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
1143 filenames)``.
1144
1145 *dirpath* is a string, the path to the directory. *dirnames* is a list of the
1146 names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``).
1147 *filenames* is a list of the names of the non-directory files in *dirpath*.
1148 Note that the names in the lists contain no path components. To get a full path
1149 (which begins with *top*) to a file or directory in *dirpath*, do
1150 ``os.path.join(dirpath, name)``.
1151
Christian Heimesfaf2f632008-01-06 16:59:19 +00001152 If optional argument *topdown* is ``True`` or not specified, the triple for a
Georg Brandl116aa622007-08-15 14:28:22 +00001153 directory is generated before the triples for any of its subdirectories
Christian Heimesfaf2f632008-01-06 16:59:19 +00001154 (directories are generated top-down). If *topdown* is ``False``, the triple for a
Georg Brandl116aa622007-08-15 14:28:22 +00001155 directory is generated after the triples for all of its subdirectories
Christian Heimesfaf2f632008-01-06 16:59:19 +00001156 (directories are generated bottom-up).
Georg Brandl116aa622007-08-15 14:28:22 +00001157
Christian Heimesfaf2f632008-01-06 16:59:19 +00001158 When *topdown* is ``True``, the caller can modify the *dirnames* list in-place
Georg Brandl116aa622007-08-15 14:28:22 +00001159 (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
1160 recurse into the subdirectories whose names remain in *dirnames*; this can be
1161 used to prune the search, impose a specific order of visiting, or even to inform
1162 :func:`walk` about directories the caller creates or renames before it resumes
Christian Heimesfaf2f632008-01-06 16:59:19 +00001163 :func:`walk` again. Modifying *dirnames* when *topdown* is ``False`` is
Georg Brandl116aa622007-08-15 14:28:22 +00001164 ineffective, because in bottom-up mode the directories in *dirnames* are
1165 generated before *dirpath* itself is generated.
1166
Christian Heimesfaf2f632008-01-06 16:59:19 +00001167 By default errors from the :func:`listdir` call are ignored. If optional
Georg Brandl116aa622007-08-15 14:28:22 +00001168 argument *onerror* is specified, it should be a function; it will be called with
1169 one argument, an :exc:`OSError` instance. It can report the error to continue
1170 with the walk, or raise the exception to abort the walk. Note that the filename
1171 is available as the ``filename`` attribute of the exception object.
1172
1173 By default, :func:`walk` will not walk down into symbolic links that resolve to
Christian Heimesfaf2f632008-01-06 16:59:19 +00001174 directories. Set *followlinks* to ``True`` to visit directories pointed to by
Georg Brandl116aa622007-08-15 14:28:22 +00001175 symlinks, on systems that support them.
1176
Georg Brandl116aa622007-08-15 14:28:22 +00001177 .. note::
1178
Christian Heimesfaf2f632008-01-06 16:59:19 +00001179 Be aware that setting *followlinks* to ``True`` can lead to infinite recursion if a
Georg Brandl116aa622007-08-15 14:28:22 +00001180 link points to a parent directory of itself. :func:`walk` does not keep track of
1181 the directories it visited already.
1182
1183 .. note::
1184
1185 If you pass a relative pathname, don't change the current working directory
1186 between resumptions of :func:`walk`. :func:`walk` never changes the current
1187 directory, and assumes that its caller doesn't either.
1188
1189 This example displays the number of bytes taken by non-directory files in each
1190 directory under the starting directory, except that it doesn't look under any
1191 CVS subdirectory::
1192
1193 import os
1194 from os.path import join, getsize
1195 for root, dirs, files in os.walk('python/Lib/email'):
Georg Brandl6911e3c2007-09-04 07:15:32 +00001196 print(root, "consumes", end=" ")
1197 print(sum(getsize(join(root, name)) for name in files), end=" ")
1198 print("bytes in", len(files), "non-directory files")
Georg Brandl116aa622007-08-15 14:28:22 +00001199 if 'CVS' in dirs:
1200 dirs.remove('CVS') # don't visit CVS directories
1201
Christian Heimesfaf2f632008-01-06 16:59:19 +00001202 In the next example, walking the tree bottom-up is essential: :func:`rmdir`
Georg Brandl116aa622007-08-15 14:28:22 +00001203 doesn't allow deleting a directory before the directory is empty::
1204
Christian Heimesfaf2f632008-01-06 16:59:19 +00001205 # Delete everything reachable from the directory named in "top",
Georg Brandl116aa622007-08-15 14:28:22 +00001206 # assuming there are no symbolic links.
1207 # CAUTION: This is dangerous! For example, if top == '/', it
1208 # could delete all your disk files.
1209 import os
1210 for root, dirs, files in os.walk(top, topdown=False):
1211 for name in files:
1212 os.remove(os.path.join(root, name))
1213 for name in dirs:
1214 os.rmdir(os.path.join(root, name))
1215
Georg Brandl116aa622007-08-15 14:28:22 +00001216
1217.. _os-process:
1218
1219Process Management
1220------------------
1221
1222These functions may be used to create and manage processes.
1223
1224The various :func:`exec\*` functions take a list of arguments for the new
1225program loaded into the process. In each case, the first of these arguments is
1226passed to the new program as its own name rather than as an argument a user may
1227have typed on a command line. For the C programmer, this is the ``argv[0]``
1228passed to a program's :cfunc:`main`. For example, ``os.execv('/bin/echo',
1229['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
1230to be ignored.
1231
1232
1233.. function:: abort()
1234
1235 Generate a :const:`SIGABRT` signal to the current process. On Unix, the default
1236 behavior is to produce a core dump; on Windows, the process immediately returns
1237 an exit code of ``3``. Be aware that programs which use :func:`signal.signal`
1238 to register a handler for :const:`SIGABRT` will behave differently.
Georg Brandlc575c902008-09-13 17:46:05 +00001239 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001240
1241
1242.. function:: execl(path, arg0, arg1, ...)
1243 execle(path, arg0, arg1, ..., env)
1244 execlp(file, arg0, arg1, ...)
1245 execlpe(file, arg0, arg1, ..., env)
1246 execv(path, args)
1247 execve(path, args, env)
1248 execvp(file, args)
1249 execvpe(file, args, env)
1250
1251 These functions all execute a new program, replacing the current process; they
1252 do not return. On Unix, the new executable is loaded into the current process,
Christian Heimesfaf2f632008-01-06 16:59:19 +00001253 and will have the same process id as the caller. Errors will be reported as
Georg Brandl48310cd2009-01-03 21:18:54 +00001254 :exc:`OSError` exceptions.
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001255
1256 The current process is replaced immediately. Open file objects and
1257 descriptors are not flushed, so if there may be data buffered
1258 on these open files, you should flush them using
1259 :func:`sys.stdout.flush` or :func:`os.fsync` before calling an
1260 :func:`exec\*` function.
Georg Brandl116aa622007-08-15 14:28:22 +00001261
Christian Heimesfaf2f632008-01-06 16:59:19 +00001262 The "l" and "v" variants of the :func:`exec\*` functions differ in how
1263 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl116aa622007-08-15 14:28:22 +00001264 to work with if the number of parameters is fixed when the code is written; the
1265 individual parameters simply become additional parameters to the :func:`execl\*`
Christian Heimesfaf2f632008-01-06 16:59:19 +00001266 functions. The "v" variants are good when the number of parameters is
Georg Brandl116aa622007-08-15 14:28:22 +00001267 variable, with the arguments being passed in a list or tuple as the *args*
1268 parameter. In either case, the arguments to the child process should start with
1269 the name of the command being run, but this is not enforced.
1270
Christian Heimesfaf2f632008-01-06 16:59:19 +00001271 The variants which include a "p" near the end (:func:`execlp`,
Georg Brandl116aa622007-08-15 14:28:22 +00001272 :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
1273 :envvar:`PATH` environment variable to locate the program *file*. When the
1274 environment is being replaced (using one of the :func:`exec\*e` variants,
1275 discussed in the next paragraph), the new environment is used as the source of
1276 the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
1277 :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
1278 locate the executable; *path* must contain an appropriate absolute or relative
1279 path.
1280
1281 For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
Christian Heimesfaf2f632008-01-06 16:59:19 +00001282 that these all end in "e"), the *env* parameter must be a mapping which is
Christian Heimesa342c012008-04-20 21:01:16 +00001283 used to define the environment variables for the new process (these are used
1284 instead of the current process' environment); the functions :func:`execl`,
Georg Brandl116aa622007-08-15 14:28:22 +00001285 :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
Georg Brandl48310cd2009-01-03 21:18:54 +00001286 inherit the environment of the current process.
Benjamin Petersone9bbc8b2008-09-28 02:06:32 +00001287
1288 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001289
1290
1291.. function:: _exit(n)
1292
1293 Exit to the system with status *n*, without calling cleanup handlers, flushing
Georg Brandlc575c902008-09-13 17:46:05 +00001294 stdio buffers, etc. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001295
1296 .. note::
1297
1298 The standard way to exit is ``sys.exit(n)``. :func:`_exit` should normally only
1299 be used in the child process after a :func:`fork`.
1300
Christian Heimesfaf2f632008-01-06 16:59:19 +00001301The following exit codes are defined and can be used with :func:`_exit`,
Georg Brandl116aa622007-08-15 14:28:22 +00001302although they are not required. These are typically used for system programs
1303written in Python, such as a mail server's external command delivery program.
1304
1305.. note::
1306
1307 Some of these may not be available on all Unix platforms, since there is some
1308 variation. These constants are defined where they are defined by the underlying
1309 platform.
1310
1311
1312.. data:: EX_OK
1313
Georg Brandlc575c902008-09-13 17:46:05 +00001314 Exit code that means no error occurred. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001315
Georg Brandl116aa622007-08-15 14:28:22 +00001316
1317.. data:: EX_USAGE
1318
1319 Exit code that means the command was used incorrectly, such as when the wrong
Georg Brandlc575c902008-09-13 17:46:05 +00001320 number of arguments are given. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001321
Georg Brandl116aa622007-08-15 14:28:22 +00001322
1323.. data:: EX_DATAERR
1324
Georg Brandlc575c902008-09-13 17:46:05 +00001325 Exit code that means the input data was incorrect. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001326
Georg Brandl116aa622007-08-15 14:28:22 +00001327
1328.. data:: EX_NOINPUT
1329
1330 Exit code that means an input file did not exist or was not readable.
Georg Brandlc575c902008-09-13 17:46:05 +00001331 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001332
Georg Brandl116aa622007-08-15 14:28:22 +00001333
1334.. data:: EX_NOUSER
1335
Georg Brandlc575c902008-09-13 17:46:05 +00001336 Exit code that means a specified user did not exist. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001337
Georg Brandl116aa622007-08-15 14:28:22 +00001338
1339.. data:: EX_NOHOST
1340
Georg Brandlc575c902008-09-13 17:46:05 +00001341 Exit code that means a specified host did not exist. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001342
Georg Brandl116aa622007-08-15 14:28:22 +00001343
1344.. data:: EX_UNAVAILABLE
1345
1346 Exit code that means that a required service is unavailable. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +00001347 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001348
Georg Brandl116aa622007-08-15 14:28:22 +00001349
1350.. data:: EX_SOFTWARE
1351
1352 Exit code that means an internal software error was detected. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +00001353 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001354
Georg Brandl116aa622007-08-15 14:28:22 +00001355
1356.. data:: EX_OSERR
1357
1358 Exit code that means an operating system error was detected, such as the
Georg Brandlc575c902008-09-13 17:46:05 +00001359 inability to fork or create a pipe. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001360
Georg Brandl116aa622007-08-15 14:28:22 +00001361
1362.. data:: EX_OSFILE
1363
1364 Exit code that means some system file did not exist, could not be opened, or had
Georg Brandlc575c902008-09-13 17:46:05 +00001365 some other kind of error. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001366
Georg Brandl116aa622007-08-15 14:28:22 +00001367
1368.. data:: EX_CANTCREAT
1369
1370 Exit code that means a user specified output file could not be created.
Georg Brandlc575c902008-09-13 17:46:05 +00001371 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001372
Georg Brandl116aa622007-08-15 14:28:22 +00001373
1374.. data:: EX_IOERR
1375
1376 Exit code that means that an error occurred while doing I/O on some file.
Georg Brandlc575c902008-09-13 17:46:05 +00001377 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001378
Georg Brandl116aa622007-08-15 14:28:22 +00001379
1380.. data:: EX_TEMPFAIL
1381
1382 Exit code that means a temporary failure occurred. This indicates something
1383 that may not really be an error, such as a network connection that couldn't be
Georg Brandlc575c902008-09-13 17:46:05 +00001384 made during a retryable operation. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001385
Georg Brandl116aa622007-08-15 14:28:22 +00001386
1387.. data:: EX_PROTOCOL
1388
1389 Exit code that means that a protocol exchange was illegal, invalid, or not
Georg Brandlc575c902008-09-13 17:46:05 +00001390 understood. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001391
Georg Brandl116aa622007-08-15 14:28:22 +00001392
1393.. data:: EX_NOPERM
1394
1395 Exit code that means that there were insufficient permissions to perform the
Georg Brandlc575c902008-09-13 17:46:05 +00001396 operation (but not intended for file system problems). Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001397
Georg Brandl116aa622007-08-15 14:28:22 +00001398
1399.. data:: EX_CONFIG
1400
1401 Exit code that means that some kind of configuration error occurred.
Georg Brandlc575c902008-09-13 17:46:05 +00001402 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001403
Georg Brandl116aa622007-08-15 14:28:22 +00001404
1405.. data:: EX_NOTFOUND
1406
1407 Exit code that means something like "an entry was not found". Availability:
Georg Brandlc575c902008-09-13 17:46:05 +00001408 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001409
Georg Brandl116aa622007-08-15 14:28:22 +00001410
1411.. function:: fork()
1412
Christian Heimesfaf2f632008-01-06 16:59:19 +00001413 Fork a child process. Return ``0`` in the child and the child's process id in the
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001414 parent. If an error occurs :exc:`OSError` is raised.
Benjamin Petersonbcd8ac32008-10-10 22:20:52 +00001415
1416 Note that some platforms including FreeBSD <= 6.3, Cygwin and OS/2 EMX have
1417 known issues when using fork() from a thread.
1418
Georg Brandlc575c902008-09-13 17:46:05 +00001419 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001420
1421
1422.. function:: forkpty()
1423
1424 Fork a child process, using a new pseudo-terminal as the child's controlling
1425 terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
1426 new child's process id in the parent, and *fd* is the file descriptor of the
1427 master end of the pseudo-terminal. For a more portable approach, use the
Christian Heimesdd15f6c2008-03-16 00:07:10 +00001428 :mod:`pty` module. If an error occurs :exc:`OSError` is raised.
Georg Brandlc575c902008-09-13 17:46:05 +00001429 Availability: some flavors of Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001430
1431
1432.. function:: kill(pid, sig)
1433
1434 .. index::
1435 single: process; killing
1436 single: process; signalling
1437
1438 Send signal *sig* to the process *pid*. Constants for the specific signals
1439 available on the host platform are defined in the :mod:`signal` module.
Georg Brandlc575c902008-09-13 17:46:05 +00001440 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001441
1442
1443.. function:: killpg(pgid, sig)
1444
1445 .. index::
1446 single: process; killing
1447 single: process; signalling
1448
Georg Brandlc575c902008-09-13 17:46:05 +00001449 Send the signal *sig* to the process group *pgid*. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001450
Georg Brandl116aa622007-08-15 14:28:22 +00001451
1452.. function:: nice(increment)
1453
1454 Add *increment* to the process's "niceness". Return the new niceness.
Georg Brandlc575c902008-09-13 17:46:05 +00001455 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001456
1457
1458.. function:: plock(op)
1459
1460 Lock program segments into memory. The value of *op* (defined in
Georg Brandlc575c902008-09-13 17:46:05 +00001461 ``<sys/lock.h>``) determines which segments are locked. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001462
1463
1464.. function:: popen(...)
1465 :noindex:
1466
1467 Run child processes, returning opened pipes for communications. These functions
1468 are described in section :ref:`os-newstreams`.
1469
1470
1471.. function:: spawnl(mode, path, ...)
1472 spawnle(mode, path, ..., env)
1473 spawnlp(mode, file, ...)
1474 spawnlpe(mode, file, ..., env)
1475 spawnv(mode, path, args)
1476 spawnve(mode, path, args, env)
1477 spawnvp(mode, file, args)
1478 spawnvpe(mode, file, args, env)
1479
1480 Execute the program *path* in a new process.
1481
1482 (Note that the :mod:`subprocess` module provides more powerful facilities for
1483 spawning new processes and retrieving their results; using that module is
Benjamin Peterson87c8d872009-06-11 22:54:11 +00001484 preferable to using these functions. Check especially the
1485 :ref:`subprocess-replacements` section.)
Georg Brandl116aa622007-08-15 14:28:22 +00001486
Christian Heimesfaf2f632008-01-06 16:59:19 +00001487 If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new
Georg Brandl116aa622007-08-15 14:28:22 +00001488 process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
1489 exits normally, or ``-signal``, where *signal* is the signal that killed the
Christian Heimesfaf2f632008-01-06 16:59:19 +00001490 process. On Windows, the process id will actually be the process handle, so can
Georg Brandl116aa622007-08-15 14:28:22 +00001491 be used with the :func:`waitpid` function.
1492
Christian Heimesfaf2f632008-01-06 16:59:19 +00001493 The "l" and "v" variants of the :func:`spawn\*` functions differ in how
1494 command-line arguments are passed. The "l" variants are perhaps the easiest
Georg Brandl116aa622007-08-15 14:28:22 +00001495 to work with if the number of parameters is fixed when the code is written; the
1496 individual parameters simply become additional parameters to the
Christian Heimesfaf2f632008-01-06 16:59:19 +00001497 :func:`spawnl\*` functions. The "v" variants are good when the number of
Georg Brandl116aa622007-08-15 14:28:22 +00001498 parameters is variable, with the arguments being passed in a list or tuple as
1499 the *args* parameter. In either case, the arguments to the child process must
1500 start with the name of the command being run.
1501
Christian Heimesfaf2f632008-01-06 16:59:19 +00001502 The variants which include a second "p" near the end (:func:`spawnlp`,
Georg Brandl116aa622007-08-15 14:28:22 +00001503 :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
1504 :envvar:`PATH` environment variable to locate the program *file*. When the
1505 environment is being replaced (using one of the :func:`spawn\*e` variants,
1506 discussed in the next paragraph), the new environment is used as the source of
1507 the :envvar:`PATH` variable. The other variants, :func:`spawnl`,
1508 :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
1509 :envvar:`PATH` variable to locate the executable; *path* must contain an
1510 appropriate absolute or relative path.
1511
1512 For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
Christian Heimesfaf2f632008-01-06 16:59:19 +00001513 (note that these all end in "e"), the *env* parameter must be a mapping
Christian Heimesa342c012008-04-20 21:01:16 +00001514 which is used to define the environment variables for the new process (they are
1515 used instead of the current process' environment); the functions
Georg Brandl116aa622007-08-15 14:28:22 +00001516 :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
Benjamin Petersond23f8222009-04-05 19:13:16 +00001517 the new process to inherit the environment of the current process. Note that
1518 keys and values in the *env* dictionary must be strings; invalid keys or
1519 values will cause the function to fail, with a return value of ``127``.
Georg Brandl116aa622007-08-15 14:28:22 +00001520
1521 As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are
1522 equivalent::
1523
1524 import os
1525 os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
1526
1527 L = ['cp', 'index.html', '/dev/null']
1528 os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
1529
1530 Availability: Unix, Windows. :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
1531 and :func:`spawnvpe` are not available on Windows.
1532
Georg Brandl116aa622007-08-15 14:28:22 +00001533
1534.. data:: P_NOWAIT
1535 P_NOWAITO
1536
1537 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1538 functions. If either of these values is given, the :func:`spawn\*` functions
Christian Heimesfaf2f632008-01-06 16:59:19 +00001539 will return as soon as the new process has been created, with the process id as
Georg Brandlc575c902008-09-13 17:46:05 +00001540 the return value. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001541
Georg Brandl116aa622007-08-15 14:28:22 +00001542
1543.. data:: P_WAIT
1544
1545 Possible value for the *mode* parameter to the :func:`spawn\*` family of
1546 functions. If this is given as *mode*, the :func:`spawn\*` functions will not
1547 return until the new process has run to completion and will return the exit code
1548 of the process the run is successful, or ``-signal`` if a signal kills the
Georg Brandlc575c902008-09-13 17:46:05 +00001549 process. Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001550
Georg Brandl116aa622007-08-15 14:28:22 +00001551
1552.. data:: P_DETACH
1553 P_OVERLAY
1554
1555 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1556 functions. These are less portable than those listed above. :const:`P_DETACH`
1557 is similar to :const:`P_NOWAIT`, but the new process is detached from the
1558 console of the calling process. If :const:`P_OVERLAY` is used, the current
1559 process will be replaced; the :func:`spawn\*` function will not return.
1560 Availability: Windows.
1561
Georg Brandl116aa622007-08-15 14:28:22 +00001562
1563.. function:: startfile(path[, operation])
1564
1565 Start a file with its associated application.
1566
1567 When *operation* is not specified or ``'open'``, this acts like double-clicking
1568 the file in Windows Explorer, or giving the file name as an argument to the
1569 :program:`start` command from the interactive command shell: the file is opened
1570 with whatever application (if any) its extension is associated.
1571
1572 When another *operation* is given, it must be a "command verb" that specifies
1573 what should be done with the file. Common verbs documented by Microsoft are
1574 ``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` and
1575 ``'find'`` (to be used on directories).
1576
1577 :func:`startfile` returns as soon as the associated application is launched.
1578 There is no option to wait for the application to close, and no way to retrieve
1579 the application's exit status. The *path* parameter is relative to the current
1580 directory. If you want to use an absolute path, make sure the first character
1581 is not a slash (``'/'``); the underlying Win32 :cfunc:`ShellExecute` function
1582 doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that
1583 the path is properly encoded for Win32. Availability: Windows.
1584
Georg Brandl116aa622007-08-15 14:28:22 +00001585
1586.. function:: system(command)
1587
1588 Execute the command (a string) in a subshell. This is implemented by calling
Georg Brandl628e6f92009-10-27 20:24:45 +00001589 the Standard C function :cfunc:`system`, and has the same limitations.
1590 Changes to :data:`sys.stdin`, etc. are not reflected in the environment of the
1591 executed command.
Georg Brandl116aa622007-08-15 14:28:22 +00001592
1593 On Unix, the return value is the exit status of the process encoded in the
1594 format specified for :func:`wait`. Note that POSIX does not specify the meaning
1595 of the return value of the C :cfunc:`system` function, so the return value of
1596 the Python function is system-dependent.
1597
1598 On Windows, the return value is that returned by the system shell after running
1599 *command*, given by the Windows environment variable :envvar:`COMSPEC`: on
1600 :program:`command.com` systems (Windows 95, 98 and ME) this is always ``0``; on
1601 :program:`cmd.exe` systems (Windows NT, 2000 and XP) this is the exit status of
1602 the command run; on systems using a non-native shell, consult your shell
1603 documentation.
1604
Georg Brandlc575c902008-09-13 17:46:05 +00001605 Availability: Unix, Windows.
Georg Brandl116aa622007-08-15 14:28:22 +00001606
1607 The :mod:`subprocess` module provides more powerful facilities for spawning new
1608 processes and retrieving their results; using that module is preferable to using
Benjamin Petersondcf97b92008-07-02 17:30:14 +00001609 this function. Use the :mod:`subprocess` module. Check especially the
1610 :ref:`subprocess-replacements` section.
Georg Brandl116aa622007-08-15 14:28:22 +00001611
1612
1613.. function:: times()
1614
1615 Return a 5-tuple of floating point numbers indicating accumulated (processor or
1616 other) times, in seconds. The items are: user time, system time, children's
1617 user time, children's system time, and elapsed real time since a fixed point in
1618 the past, in that order. See the Unix manual page :manpage:`times(2)` or the
Georg Brandlc575c902008-09-13 17:46:05 +00001619 corresponding Windows Platform API documentation. Availability: Unix,
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001620 Windows. On Windows, only the first two items are filled, the others are zero.
Georg Brandl116aa622007-08-15 14:28:22 +00001621
1622
1623.. function:: wait()
1624
1625 Wait for completion of a child process, and return a tuple containing its pid
1626 and exit status indication: a 16-bit number, whose low byte is the signal number
1627 that killed the process, and whose high byte is the exit status (if the signal
1628 number is zero); the high bit of the low byte is set if a core file was
Georg Brandlc575c902008-09-13 17:46:05 +00001629 produced. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001630
1631
1632.. function:: waitpid(pid, options)
1633
1634 The details of this function differ on Unix and Windows.
1635
1636 On Unix: Wait for completion of a child process given by process id *pid*, and
1637 return a tuple containing its process id and exit status indication (encoded as
1638 for :func:`wait`). The semantics of the call are affected by the value of the
1639 integer *options*, which should be ``0`` for normal operation.
1640
1641 If *pid* is greater than ``0``, :func:`waitpid` requests status information for
1642 that specific process. If *pid* is ``0``, the request is for the status of any
1643 child in the process group of the current process. If *pid* is ``-1``, the
1644 request pertains to any child of the current process. If *pid* is less than
1645 ``-1``, status is requested for any process in the process group ``-pid`` (the
1646 absolute value of *pid*).
1647
Benjamin Peterson4cd6a952008-08-17 20:23:46 +00001648 An :exc:`OSError` is raised with the value of errno when the syscall
1649 returns -1.
1650
Georg Brandl116aa622007-08-15 14:28:22 +00001651 On Windows: Wait for completion of a process given by process handle *pid*, and
1652 return a tuple containing *pid*, and its exit status shifted left by 8 bits
1653 (shifting makes cross-platform use of the function easier). A *pid* less than or
1654 equal to ``0`` has no special meaning on Windows, and raises an exception. The
1655 value of integer *options* has no effect. *pid* can refer to any process whose
1656 id is known, not necessarily a child process. The :func:`spawn` functions called
1657 with :const:`P_NOWAIT` return suitable process handles.
1658
1659
1660.. function:: wait3([options])
1661
1662 Similar to :func:`waitpid`, except no process id argument is given and a
1663 3-element tuple containing the child's process id, exit status indication, and
1664 resource usage information is returned. Refer to :mod:`resource`.\
1665 :func:`getrusage` for details on resource usage information. The option
1666 argument is the same as that provided to :func:`waitpid` and :func:`wait4`.
1667 Availability: Unix.
1668
Georg Brandl116aa622007-08-15 14:28:22 +00001669
1670.. function:: wait4(pid, options)
1671
1672 Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
1673 process id, exit status indication, and resource usage information is returned.
1674 Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage
1675 information. The arguments to :func:`wait4` are the same as those provided to
1676 :func:`waitpid`. Availability: Unix.
1677
Georg Brandl116aa622007-08-15 14:28:22 +00001678
1679.. data:: WNOHANG
1680
1681 The option for :func:`waitpid` to return immediately if no child process status
1682 is available immediately. The function returns ``(0, 0)`` in this case.
Georg Brandlc575c902008-09-13 17:46:05 +00001683 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001684
1685
1686.. data:: WCONTINUED
1687
1688 This option causes child processes to be reported if they have been continued
1689 from a job control stop since their status was last reported. Availability: Some
1690 Unix systems.
1691
Georg Brandl116aa622007-08-15 14:28:22 +00001692
1693.. data:: WUNTRACED
1694
1695 This option causes child processes to be reported if they have been stopped but
1696 their current state has not been reported since they were stopped. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +00001697 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001698
Georg Brandl116aa622007-08-15 14:28:22 +00001699
1700The following functions take a process status code as returned by
1701:func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be
1702used to determine the disposition of a process.
1703
Georg Brandl116aa622007-08-15 14:28:22 +00001704.. function:: WCOREDUMP(status)
1705
Christian Heimesfaf2f632008-01-06 16:59:19 +00001706 Return ``True`` if a core dump was generated for the process, otherwise
Georg Brandlc575c902008-09-13 17:46:05 +00001707 return ``False``. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001708
Georg Brandl116aa622007-08-15 14:28:22 +00001709
1710.. function:: WIFCONTINUED(status)
1711
Christian Heimesfaf2f632008-01-06 16:59:19 +00001712 Return ``True`` if the process has been continued from a job control stop,
1713 otherwise return ``False``. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001714
Georg Brandl116aa622007-08-15 14:28:22 +00001715
1716.. function:: WIFSTOPPED(status)
1717
Christian Heimesfaf2f632008-01-06 16:59:19 +00001718 Return ``True`` if the process has been stopped, otherwise return
Georg Brandl116aa622007-08-15 14:28:22 +00001719 ``False``. Availability: Unix.
1720
1721
1722.. function:: WIFSIGNALED(status)
1723
Christian Heimesfaf2f632008-01-06 16:59:19 +00001724 Return ``True`` if the process exited due to a signal, otherwise return
Georg Brandlc575c902008-09-13 17:46:05 +00001725 ``False``. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001726
1727
1728.. function:: WIFEXITED(status)
1729
Christian Heimesfaf2f632008-01-06 16:59:19 +00001730 Return ``True`` if the process exited using the :manpage:`exit(2)` system call,
Georg Brandlc575c902008-09-13 17:46:05 +00001731 otherwise return ``False``. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001732
1733
1734.. function:: WEXITSTATUS(status)
1735
1736 If ``WIFEXITED(status)`` is true, return the integer parameter to the
1737 :manpage:`exit(2)` system call. Otherwise, the return value is meaningless.
Georg Brandlc575c902008-09-13 17:46:05 +00001738 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001739
1740
1741.. function:: WSTOPSIG(status)
1742
Georg Brandlc575c902008-09-13 17:46:05 +00001743 Return the signal which caused the process to stop. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001744
1745
1746.. function:: WTERMSIG(status)
1747
Georg Brandlc575c902008-09-13 17:46:05 +00001748 Return the signal which caused the process to exit. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001749
1750
1751.. _os-path:
1752
1753Miscellaneous System Information
1754--------------------------------
1755
1756
1757.. function:: confstr(name)
1758
1759 Return string-valued system configuration values. *name* specifies the
1760 configuration value to retrieve; it may be a string which is the name of a
1761 defined system value; these names are specified in a number of standards (POSIX,
1762 Unix 95, Unix 98, and others). Some platforms define additional names as well.
1763 The names known to the host operating system are given as the keys of the
1764 ``confstr_names`` dictionary. For configuration variables not included in that
1765 mapping, passing an integer for *name* is also accepted. Availability:
Georg Brandlc575c902008-09-13 17:46:05 +00001766 Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001767
1768 If the configuration value specified by *name* isn't defined, ``None`` is
1769 returned.
1770
1771 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
1772 specific value for *name* is not supported by the host system, even if it is
1773 included in ``confstr_names``, an :exc:`OSError` is raised with
1774 :const:`errno.EINVAL` for the error number.
1775
1776
1777.. data:: confstr_names
1778
1779 Dictionary mapping names accepted by :func:`confstr` to the integer values
1780 defined for those names by the host operating system. This can be used to
Georg Brandlc575c902008-09-13 17:46:05 +00001781 determine the set of names known to the system. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001782
1783
1784.. function:: getloadavg()
1785
Christian Heimesa62da1d2008-01-12 19:39:10 +00001786 Return the number of processes in the system run queue averaged over the last
1787 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was
Georg Brandlf08a9dd2008-06-10 16:57:31 +00001788 unobtainable. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001789
Georg Brandl116aa622007-08-15 14:28:22 +00001790
1791.. function:: sysconf(name)
1792
1793 Return integer-valued system configuration values. If the configuration value
1794 specified by *name* isn't defined, ``-1`` is returned. The comments regarding
1795 the *name* parameter for :func:`confstr` apply here as well; the dictionary that
1796 provides information on the known names is given by ``sysconf_names``.
Georg Brandlc575c902008-09-13 17:46:05 +00001797 Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001798
1799
1800.. data:: sysconf_names
1801
1802 Dictionary mapping names accepted by :func:`sysconf` to the integer values
1803 defined for those names by the host operating system. This can be used to
Georg Brandlc575c902008-09-13 17:46:05 +00001804 determine the set of names known to the system. Availability: Unix.
Georg Brandl116aa622007-08-15 14:28:22 +00001805
Christian Heimesfaf2f632008-01-06 16:59:19 +00001806The following data values are used to support path manipulation operations. These
Georg Brandl116aa622007-08-15 14:28:22 +00001807are defined for all platforms.
1808
1809Higher-level operations on pathnames are defined in the :mod:`os.path` module.
1810
1811
1812.. data:: curdir
1813
1814 The constant string used by the operating system to refer to the current
Georg Brandlc575c902008-09-13 17:46:05 +00001815 directory. This is ``'.'`` for Windows and POSIX. Also available via
1816 :mod:`os.path`.
Georg Brandl116aa622007-08-15 14:28:22 +00001817
1818
1819.. data:: pardir
1820
1821 The constant string used by the operating system to refer to the parent
Georg Brandlc575c902008-09-13 17:46:05 +00001822 directory. This is ``'..'`` for Windows and POSIX. Also available via
1823 :mod:`os.path`.
Georg Brandl116aa622007-08-15 14:28:22 +00001824
1825
1826.. data:: sep
1827
Georg Brandlc575c902008-09-13 17:46:05 +00001828 The character used by the operating system to separate pathname components.
1829 This is ``'/'`` for POSIX and ``'\\'`` for Windows. Note that knowing this
1830 is not sufficient to be able to parse or concatenate pathnames --- use
Georg Brandl116aa622007-08-15 14:28:22 +00001831 :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
1832 useful. Also available via :mod:`os.path`.
1833
1834
1835.. data:: altsep
1836
1837 An alternative character used by the operating system to separate pathname
1838 components, or ``None`` if only one separator character exists. This is set to
1839 ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
1840 :mod:`os.path`.
1841
1842
1843.. data:: extsep
1844
1845 The character which separates the base filename from the extension; for example,
1846 the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.
1847
Georg Brandl116aa622007-08-15 14:28:22 +00001848
1849.. data:: pathsep
1850
1851 The character conventionally used by the operating system to separate search
1852 path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
1853 Windows. Also available via :mod:`os.path`.
1854
1855
1856.. data:: defpath
1857
1858 The default search path used by :func:`exec\*p\*` and :func:`spawn\*p\*` if the
1859 environment doesn't have a ``'PATH'`` key. Also available via :mod:`os.path`.
1860
1861
1862.. data:: linesep
1863
1864 The string used to separate (or, rather, terminate) lines on the current
Georg Brandlc575c902008-09-13 17:46:05 +00001865 platform. This may be a single character, such as ``'\n'`` for POSIX, or
1866 multiple characters, for example, ``'\r\n'`` for Windows. Do not use
1867 *os.linesep* as a line terminator when writing files opened in text mode (the
1868 default); use a single ``'\n'`` instead, on all platforms.
Georg Brandl116aa622007-08-15 14:28:22 +00001869
1870
1871.. data:: devnull
1872
Georg Brandlc575c902008-09-13 17:46:05 +00001873 The file path of the null device. For example: ``'/dev/null'`` for POSIX.
1874 Also available via :mod:`os.path`.
Georg Brandl116aa622007-08-15 14:28:22 +00001875
Georg Brandl116aa622007-08-15 14:28:22 +00001876
1877.. _os-miscfunc:
1878
1879Miscellaneous Functions
1880-----------------------
1881
1882
1883.. function:: urandom(n)
1884
1885 Return a string of *n* random bytes suitable for cryptographic use.
1886
1887 This function returns random bytes from an OS-specific randomness source. The
1888 returned data should be unpredictable enough for cryptographic applications,
1889 though its exact quality depends on the OS implementation. On a UNIX-like
1890 system this will query /dev/urandom, and on Windows it will use CryptGenRandom.
1891 If a randomness source is not found, :exc:`NotImplementedError` will be raised.