blob: 1b5eb4976f8b978f2709e0d48a48a7549cad0a22 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`os` --- Miscellaneous operating system interfaces
3=======================================================
4
5.. module:: os
6 :synopsis: Miscellaneous operating system interfaces.
7
8
9This module provides a more portable way of using operating system dependent
10functionality than importing a operating system dependent built-in module like
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011:mod:`posix` or :mod:`nt`. If you just want to read or write a file see
12:func:`open`, if you want to manipulate paths, see the :mod:`os.path`
13module, and if you want to read all the lines in all the files on the
Guido van Rossum2cc30da2007-11-02 23:46:40 +000014command line see the :mod:`fileinput` module. For creating temporary
15files and directories see the :mod:`tempfile` module, and for high-level
16file and directory handling see the :mod:`shutil` module.
Georg Brandl116aa622007-08-15 14:28:22 +000017
18This module searches for an operating system dependent built-in module like
19:mod:`mac` or :mod:`posix` and exports the same functions and data as found
20there. The design of all Python's built-in operating system dependent modules
21is such that as long as the same functionality is available, it uses the same
22interface; for example, the function ``os.stat(path)`` returns stat information
23about *path* in the same format (which happens to have originated with the POSIX
24interface).
25
26Extensions peculiar to a particular operating system are also available through
27the :mod:`os` module, but using them is of course a threat to portability!
28
29Note that after the first time :mod:`os` is imported, there is *no* performance
30penalty in using functions from :mod:`os` instead of directly from the operating
31system dependent built-in module, so there should be *no* reason not to use
32:mod:`os`!
33
34The :mod:`os` module contains many functions and data values. The items below
35and in the following sub-sections are all available directly from the :mod:`os`
36module.
37
Georg Brandl116aa622007-08-15 14:28:22 +000038.. exception:: error
39
40 .. index:: module: errno
41
42 This exception is raised when a function returns a system-related error (not for
43 illegal argument types or other incidental errors). This is also known as the
44 built-in exception :exc:`OSError`. The accompanying value is a pair containing
45 the numeric error code from :cdata:`errno` and the corresponding string, as
46 would be printed by the C function :cfunc:`perror`. See the module
47 :mod:`errno`, which contains names for the error codes defined by the underlying
48 operating system.
49
50 When exceptions are classes, this exception carries two attributes,
51 :attr:`errno` and :attr:`strerror`. The first holds the value of the C
52 :cdata:`errno` variable, and the latter holds the corresponding error message
53 from :cfunc:`strerror`. For exceptions that involve a file system path (such as
54 :func:`chdir` or :func:`unlink`), the exception instance will contain a third
55 attribute, :attr:`filename`, which is the file name passed to the function.
56
57
58.. data:: name
59
60 The name of the operating system dependent module imported. The following names
61 have currently been registered: ``'posix'``, ``'nt'``, ``'mac'``, ``'os2'``,
Skip Montanaro7a98be22007-08-16 14:35:24 +000062 ``'ce'``, ``'java'``.
Georg Brandl116aa622007-08-15 14:28:22 +000063
64
65.. data:: path
66
67 The corresponding operating system dependent standard module for pathname
68 operations, such as :mod:`posixpath` or :mod:`macpath`. Thus, given the proper
69 imports, ``os.path.split(file)`` is equivalent to but more portable than
70 ``posixpath.split(file)``. Note that this is also an importable module: it may
71 be imported directly as :mod:`os.path`.
72
73
74.. _os-procinfo:
75
76Process Parameters
77------------------
78
79These functions and data items provide information and operate on the current
80process and user.
81
82
83.. data:: environ
84
85 A mapping object representing the string environment. For example,
86 ``environ['HOME']`` is the pathname of your home directory (on some platforms),
87 and is equivalent to ``getenv("HOME")`` in C.
88
89 This mapping is captured the first time the :mod:`os` module is imported,
90 typically during Python startup as part of processing :file:`site.py`. Changes
91 to the environment made after this time are not reflected in ``os.environ``,
92 except for changes made by modifying ``os.environ`` directly.
93
94 If the platform supports the :func:`putenv` function, this mapping may be used
95 to modify the environment as well as query the environment. :func:`putenv` will
96 be called automatically when the mapping is modified.
97
98 .. note::
99
100 Calling :func:`putenv` directly does not change ``os.environ``, so it's better
101 to modify ``os.environ``.
102
103 .. note::
104
105 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may cause
106 memory leaks. Refer to the system documentation for :cfunc:`putenv`.
107
108 If :func:`putenv` is not provided, a modified copy of this mapping may be
109 passed to the appropriate process-creation functions to cause child processes
110 to use a modified environment.
111
Georg Brandl9afde1c2007-11-01 20:32:30 +0000112 If the platform supports the :func:`unsetenv` function, you can delete items in
Georg Brandl116aa622007-08-15 14:28:22 +0000113 this mapping to unset environment variables. :func:`unsetenv` will be called
Georg Brandl9afde1c2007-11-01 20:32:30 +0000114 automatically when an item is deleted from ``os.environ``, and when
115 one of the :meth:`pop` or :meth:`clear` methods is called.
116
117 .. versionchanged:: 2.6
118 Also unset environment variables when calling :meth:`os.environ.clear`
119 and :meth:`os.environ.pop`.
Georg Brandl116aa622007-08-15 14:28:22 +0000120
121
122.. function:: chdir(path)
123 fchdir(fd)
124 getcwd()
125 :noindex:
126
127 These functions are described in :ref:`os-file-dir`.
128
129
130.. function:: ctermid()
131
132 Return the filename corresponding to the controlling terminal of the process.
133 Availability: Unix.
134
135
136.. function:: getegid()
137
138 Return the effective group id of the current process. This corresponds to the
139 'set id' bit on the file being executed in the current process. Availability:
140 Unix.
141
142
143.. function:: geteuid()
144
145 .. index:: single: user; effective id
146
147 Return the current process' effective user id. Availability: Unix.
148
149
150.. function:: getgid()
151
152 .. index:: single: process; group
153
154 Return the real group id of the current process. Availability: Unix.
155
156
157.. function:: getgroups()
158
159 Return list of supplemental group ids associated with the current process.
160 Availability: Unix.
161
162
163.. function:: getlogin()
164
165 Return the name of the user logged in on the controlling terminal of the
166 process. For most purposes, it is more useful to use the environment variable
167 :envvar:`LOGNAME` to find out who the user is, or
168 ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the currently
169 effective user ID. Availability: Unix.
170
171
172.. function:: getpgid(pid)
173
174 Return the process group id of the process with process id *pid*. If *pid* is 0,
175 the process group id of the current process is returned. Availability: Unix.
176
Georg Brandl116aa622007-08-15 14:28:22 +0000177
178.. function:: getpgrp()
179
180 .. index:: single: process; group
181
182 Return the id of the current process group. Availability: Unix.
183
184
185.. function:: getpid()
186
187 .. index:: single: process; id
188
189 Return the current process id. Availability: Unix, Windows.
190
191
192.. function:: getppid()
193
194 .. index:: single: process; id of parent
195
196 Return the parent's process id. Availability: Unix.
197
198
199.. function:: getuid()
200
201 .. index:: single: user; id
202
203 Return the current process' user id. Availability: Unix.
204
205
206.. function:: getenv(varname[, value])
207
208 Return the value of the environment variable *varname* if it exists, or *value*
209 if it doesn't. *value* defaults to ``None``. Availability: most flavors of
210 Unix, Windows.
211
212
213.. function:: putenv(varname, value)
214
215 .. index:: single: environment variables; setting
216
217 Set the environment variable named *varname* to the string *value*. Such
218 changes to the environment affect subprocesses started with :func:`os.system`,
219 :func:`popen` or :func:`fork` and :func:`execv`. Availability: most flavors of
220 Unix, Windows.
221
222 .. note::
223
224 On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may cause
225 memory leaks. Refer to the system documentation for putenv.
226
227 When :func:`putenv` is supported, assignments to items in ``os.environ`` are
228 automatically translated into corresponding calls to :func:`putenv`; however,
229 calls to :func:`putenv` don't update ``os.environ``, so it is actually
230 preferable to assign to items of ``os.environ``.
231
232
233.. function:: setegid(egid)
234
235 Set the current process's effective group id. Availability: Unix.
236
237
238.. function:: seteuid(euid)
239
240 Set the current process's effective user id. Availability: Unix.
241
242
243.. function:: setgid(gid)
244
245 Set the current process' group id. Availability: Unix.
246
247
248.. function:: setgroups(groups)
249
250 Set the list of supplemental group ids associated with the current process to
251 *groups*. *groups* must be a sequence, and each element must be an integer
252 identifying a group. This operation is typical available only to the superuser.
253 Availability: Unix.
254
Georg Brandl116aa622007-08-15 14:28:22 +0000255
256.. function:: setpgrp()
257
258 Calls the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on
259 which version is implemented (if any). See the Unix manual for the semantics.
260 Availability: Unix.
261
262
263.. function:: setpgid(pid, pgrp)
264
265 Calls the system call :cfunc:`setpgid` to set the process group id of the
266 process with id *pid* to the process group with id *pgrp*. See the Unix manual
267 for the semantics. Availability: Unix.
268
269
270.. function:: setreuid(ruid, euid)
271
272 Set the current process's real and effective user ids. Availability: Unix.
273
274
275.. function:: setregid(rgid, egid)
276
277 Set the current process's real and effective group ids. Availability: Unix.
278
279
280.. function:: getsid(pid)
281
282 Calls the system call :cfunc:`getsid`. See the Unix manual for the semantics.
283 Availability: Unix.
284
Georg Brandl116aa622007-08-15 14:28:22 +0000285
286.. function:: setsid()
287
288 Calls the system call :cfunc:`setsid`. See the Unix manual for the semantics.
289 Availability: Unix.
290
291
292.. function:: setuid(uid)
293
294 .. index:: single: user; id, setting
295
296 Set the current process' user id. Availability: Unix.
297
298.. % placed in this section since it relates to errno.... a little weak
299
300
301.. function:: strerror(code)
302
303 Return the error message corresponding to the error code in *code*.
304 Availability: Unix, Windows.
305
306
307.. function:: umask(mask)
308
309 Set the current numeric umask and returns the previous umask. Availability:
310 Unix, Windows.
311
312
313.. function:: uname()
314
315 .. index::
316 single: gethostname() (in module socket)
317 single: gethostbyaddr() (in module socket)
318
319 Return a 5-tuple containing information identifying the current operating
320 system. The tuple contains 5 strings: ``(sysname, nodename, release, version,
321 machine)``. Some systems truncate the nodename to 8 characters or to the
322 leading component; a better way to get the hostname is
323 :func:`socket.gethostname` or even
324 ``socket.gethostbyaddr(socket.gethostname())``. Availability: recent flavors of
325 Unix.
326
327
328.. function:: unsetenv(varname)
329
330 .. index:: single: environment variables; deleting
331
332 Unset (delete) the environment variable named *varname*. Such changes to the
333 environment affect subprocesses started with :func:`os.system`, :func:`popen` or
334 :func:`fork` and :func:`execv`. Availability: most flavors of Unix, Windows.
335
336 When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is
337 automatically translated into a corresponding call to :func:`unsetenv`; however,
338 calls to :func:`unsetenv` don't update ``os.environ``, so it is actually
339 preferable to delete items of ``os.environ``.
340
341
342.. _os-newstreams:
343
344File Object Creation
345--------------------
346
347These functions create new file objects. (See also :func:`open`.)
348
349
350.. function:: fdopen(fd[, mode[, bufsize]])
351
352 .. index:: single: I/O control; buffering
353
354 Return an open file object connected to the file descriptor *fd*. The *mode*
355 and *bufsize* arguments have the same meaning as the corresponding arguments to
356 the built-in :func:`open` function. Availability: Macintosh, Unix, Windows.
357
Georg Brandl55ac8f02007-09-01 13:51:09 +0000358 When specified, the *mode* argument must start with one of the letters
359 ``'r'``, ``'w'``, or ``'a'``, otherwise a :exc:`ValueError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000360
Georg Brandl55ac8f02007-09-01 13:51:09 +0000361 On Unix, when the *mode* argument starts with ``'a'``, the *O_APPEND* flag is
362 set on the file descriptor (which the :cfunc:`fdopen` implementation already
363 does on most platforms).
Georg Brandl116aa622007-08-15 14:28:22 +0000364
365
366.. function:: popen(command[, mode[, bufsize]])
367
368 Open a pipe to or from *command*. The return value is an open file object
369 connected to the pipe, which can be read or written depending on whether *mode*
370 is ``'r'`` (default) or ``'w'``. The *bufsize* argument has the same meaning as
371 the corresponding argument to the built-in :func:`open` function. The exit
372 status of the command (encoded in the format specified for :func:`wait`) is
373 available as the return value of the :meth:`close` method of the file object,
374 except that when the exit status is zero (termination without errors), ``None``
375 is returned. Availability: Macintosh, Unix, Windows.
376
377 .. deprecated:: 2.6
378 This function is obsolete. Use the :mod:`subprocess` module.
379
Georg Brandl116aa622007-08-15 14:28:22 +0000380
Georg Brandl116aa622007-08-15 14:28:22 +0000381.. _os-fd-ops:
382
383File Descriptor Operations
384--------------------------
385
386These functions operate on I/O streams referenced using file descriptors.
387
388File descriptors are small integers corresponding to a file that has been opened
389by the current process. For example, standard input is usually file descriptor
3900, standard output is 1, and standard error is 2. Further files opened by a
391process will then be assigned 3, 4, 5, and so forth. The name "file descriptor"
392is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
393by file descriptors.
394
395
396.. function:: close(fd)
397
398 Close file descriptor *fd*. Availability: Macintosh, Unix, Windows.
399
400 .. note::
401
402 This function is intended for low-level I/O and must be applied to a file
403 descriptor as returned by :func:`open` or :func:`pipe`. To close a "file
404 object" returned by the built-in function :func:`open` or by :func:`popen` or
405 :func:`fdopen`, use its :meth:`close` method.
406
407
408.. function:: dup(fd)
409
410 Return a duplicate of file descriptor *fd*. Availability: Macintosh, Unix,
411 Windows.
412
413
414.. function:: dup2(fd, fd2)
415
416 Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary.
417 Availability: Macintosh, Unix, Windows.
418
419
Christian Heimes4e30a842007-11-30 22:12:06 +0000420.. function:: fchmod(fd, mode)
421
422 Change the mode of the file given by *fd* to the numeric *mode*. See the docs
423 for :func:`chmod` for possible values of *mode*. Availability: Unix.
424
Christian Heimes93852662007-12-01 12:22:32 +0000425 .. versionadded:: 2.6
426
Christian Heimes4e30a842007-11-30 22:12:06 +0000427
428.. function:: fchown(fd, uid, gid)
429
430 Change the owner and group id of the file given by *fd* to the numeric *uid*
431 and *gid*. To leave one of the ids unchanged, set it to -1.
432 Availability: Unix.
433
Christian Heimes93852662007-12-01 12:22:32 +0000434 .. versionadded:: 2.6
435
Christian Heimes4e30a842007-11-30 22:12:06 +0000436
Georg Brandl116aa622007-08-15 14:28:22 +0000437.. function:: fdatasync(fd)
438
439 Force write of file with filedescriptor *fd* to disk. Does not force update of
440 metadata. Availability: Unix.
441
442
443.. function:: fpathconf(fd, name)
444
445 Return system configuration information relevant to an open file. *name*
446 specifies the configuration value to retrieve; it may be a string which is the
447 name of a defined system value; these names are specified in a number of
448 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
449 additional names as well. The names known to the host operating system are
450 given in the ``pathconf_names`` dictionary. For configuration variables not
451 included in that mapping, passing an integer for *name* is also accepted.
452 Availability: Macintosh, Unix.
453
454 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
455 specific value for *name* is not supported by the host system, even if it is
456 included in ``pathconf_names``, an :exc:`OSError` is raised with
457 :const:`errno.EINVAL` for the error number.
458
459
460.. function:: fstat(fd)
461
462 Return status for file descriptor *fd*, like :func:`stat`. Availability:
463 Macintosh, Unix, Windows.
464
465
466.. function:: fstatvfs(fd)
467
468 Return information about the filesystem containing the file associated with file
469 descriptor *fd*, like :func:`statvfs`. Availability: Unix.
470
471
472.. function:: fsync(fd)
473
474 Force write of file with filedescriptor *fd* to disk. On Unix, this calls the
475 native :cfunc:`fsync` function; on Windows, the MS :cfunc:`_commit` function.
476
477 If you're starting with a Python file object *f*, first do ``f.flush()``, and
478 then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated
479 with *f* are written to disk. Availability: Macintosh, Unix, and Windows
480 starting in 2.2.3.
481
482
483.. function:: ftruncate(fd, length)
484
485 Truncate the file corresponding to file descriptor *fd*, so that it is at most
486 *length* bytes in size. Availability: Macintosh, Unix.
487
488
489.. function:: isatty(fd)
490
491 Return ``True`` if the file descriptor *fd* is open and connected to a
492 tty(-like) device, else ``False``. Availability: Macintosh, Unix.
493
494
495.. function:: lseek(fd, pos, how)
496
497 Set the current position of file descriptor *fd* to position *pos*, modified by
498 *how*: ``0`` to set the position relative to the beginning of the file; ``1`` to
499 set it relative to the current position; ``2`` to set it relative to the end of
500 the file. Availability: Macintosh, Unix, Windows.
501
502
503.. function:: open(file, flags[, mode])
504
505 Open the file *file* and set various flags according to *flags* and possibly its
506 mode according to *mode*. The default *mode* is ``0777`` (octal), and the
507 current umask value is first masked out. Return the file descriptor for the
508 newly opened file. Availability: Macintosh, Unix, Windows.
509
510 For a description of the flag and mode values, see the C run-time documentation;
511 flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
512 this module too (see below).
513
514 .. note::
515
516 This function is intended for low-level I/O. For normal usage, use the built-in
517 function :func:`open`, which returns a "file object" with :meth:`read` and
518 :meth:`write` methods (and many more). To wrap a file descriptor in a "file
519 object", use :func:`fdopen`.
520
521
522.. function:: openpty()
523
524 .. index:: module: pty
525
526 Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master,
527 slave)`` for the pty and the tty, respectively. For a (slightly) more portable
528 approach, use the :mod:`pty` module. Availability: Macintosh, Some flavors of
529 Unix.
530
531
532.. function:: pipe()
533
534 Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading
535 and writing, respectively. Availability: Macintosh, Unix, Windows.
536
537
538.. function:: read(fd, n)
539
540 Read at most *n* bytes from file descriptor *fd*. Return a string containing the
541 bytes read. If the end of the file referred to by *fd* has been reached, an
542 empty string is returned. Availability: Macintosh, Unix, Windows.
543
544 .. note::
545
546 This function is intended for low-level I/O and must be applied to a file
547 descriptor as returned by :func:`open` or :func:`pipe`. To read a "file object"
548 returned by the built-in function :func:`open` or by :func:`popen` or
549 :func:`fdopen`, or ``sys.stdin``, use its :meth:`read` or :meth:`readline`
550 methods.
551
552
553.. function:: tcgetpgrp(fd)
554
555 Return the process group associated with the terminal given by *fd* (an open
556 file descriptor as returned by :func:`open`). Availability: Macintosh, Unix.
557
558
559.. function:: tcsetpgrp(fd, pg)
560
561 Set the process group associated with the terminal given by *fd* (an open file
562 descriptor as returned by :func:`open`) to *pg*. Availability: Macintosh, Unix.
563
564
565.. function:: ttyname(fd)
566
567 Return a string which specifies the terminal device associated with
Georg Brandl9afde1c2007-11-01 20:32:30 +0000568 file descriptor *fd*. If *fd* is not associated with a terminal device, an
Georg Brandl116aa622007-08-15 14:28:22 +0000569 exception is raised. Availability:Macintosh, Unix.
570
571
572.. function:: write(fd, str)
573
574 Write the string *str* to file descriptor *fd*. Return the number of bytes
575 actually written. Availability: Macintosh, Unix, Windows.
576
577 .. note::
578
579 This function is intended for low-level I/O and must be applied to a file
580 descriptor as returned by :func:`open` or :func:`pipe`. To write a "file
581 object" returned by the built-in function :func:`open` or by :func:`popen` or
582 :func:`fdopen`, or ``sys.stdout`` or ``sys.stderr``, use its :meth:`write`
583 method.
584
585The following data items are available for use in constructing the *flags*
586parameter to the :func:`open` function. Some items will not be available on all
587platforms. For descriptions of their availability and use, consult
588:manpage:`open(2)`.
589
590
591.. data:: O_RDONLY
592 O_WRONLY
593 O_RDWR
594 O_APPEND
595 O_CREAT
596 O_EXCL
597 O_TRUNC
598
599 Options for the *flag* argument to the :func:`open` function. These can be
600 bit-wise OR'd together. Availability: Macintosh, Unix, Windows.
601
602
603.. data:: O_DSYNC
604 O_RSYNC
605 O_SYNC
606 O_NDELAY
607 O_NONBLOCK
608 O_NOCTTY
609 O_SHLOCK
610 O_EXLOCK
611
612 More options for the *flag* argument to the :func:`open` function. Availability:
613 Macintosh, Unix.
614
615
616.. data:: O_BINARY
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000617 O_NOINHERIT
Georg Brandl116aa622007-08-15 14:28:22 +0000618 O_SHORT_LIVED
619 O_TEMPORARY
620 O_RANDOM
621 O_SEQUENTIAL
622 O_TEXT
623
624 Options for the *flag* argument to the :func:`open` function. These can be
625 bit-wise OR'd together. Availability: Windows.
626
627
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000628.. data:: O_DIRECT
629 O_DIRECTORY
630 O_NOFOLLOW
631 O_NOATIME
632
633 Options for the *flag* argument to the :func:`open` function. These are
634 GNU extensions and not present if they are not defined by the C library.
635
636
Georg Brandl116aa622007-08-15 14:28:22 +0000637.. data:: SEEK_SET
638 SEEK_CUR
639 SEEK_END
640
641 Parameters to the :func:`lseek` function. Their values are 0, 1, and 2,
642 respectively. Availability: Windows, Macintosh, Unix.
643
Georg Brandl116aa622007-08-15 14:28:22 +0000644
645.. _os-file-dir:
646
647Files and Directories
648---------------------
649
650
651.. function:: access(path, mode)
652
653 Use the real uid/gid to test for access to *path*. Note that most operations
654 will use the effective uid/gid, therefore this routine can be used in a
655 suid/sgid environment to test if the invoking user has the specified access to
656 *path*. *mode* should be :const:`F_OK` to test the existence of *path*, or it
657 can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and
658 :const:`X_OK` to test permissions. Return :const:`True` if access is allowed,
659 :const:`False` if not. See the Unix man page :manpage:`access(2)` for more
660 information. Availability: Macintosh, Unix, Windows.
661
662 .. note::
663
664 Using :func:`access` to check if a user is authorized to e.g. open a file before
665 actually doing so using :func:`open` creates a security hole, because the user
666 might exploit the short time interval between checking and opening the file to
667 manipulate it.
668
669 .. note::
670
671 I/O operations may fail even when :func:`access` indicates that they would
672 succeed, particularly for operations on network filesystems which may have
673 permissions semantics beyond the usual POSIX permission-bit model.
674
675
676.. data:: F_OK
677
678 Value to pass as the *mode* parameter of :func:`access` to test the existence of
679 *path*.
680
681
682.. data:: R_OK
683
684 Value to include in the *mode* parameter of :func:`access` to test the
685 readability of *path*.
686
687
688.. data:: W_OK
689
690 Value to include in the *mode* parameter of :func:`access` to test the
691 writability of *path*.
692
693
694.. data:: X_OK
695
696 Value to include in the *mode* parameter of :func:`access` to determine if
697 *path* can be executed.
698
699
700.. function:: chdir(path)
701
702 .. index:: single: directory; changing
703
704 Change the current working directory to *path*. Availability: Macintosh, Unix,
705 Windows.
706
707
708.. function:: fchdir(fd)
709
710 Change the current working directory to the directory represented by the file
711 descriptor *fd*. The descriptor must refer to an opened directory, not an open
712 file. Availability: Unix.
713
Georg Brandl116aa622007-08-15 14:28:22 +0000714
715.. function:: getcwd()
716
717 Return a string representing the current working directory. Availability:
718 Macintosh, Unix, Windows.
719
720
721.. function:: getcwdu()
722
723 Return a Unicode object representing the current working directory.
724 Availability: Macintosh, Unix, Windows.
725
Georg Brandl116aa622007-08-15 14:28:22 +0000726
727.. function:: chflags(path, flags)
728
729 Set the flags of *path* to the numeric *flags*. *flags* may take a combination
730 (bitwise OR) of the following values (as defined in the :mod:`stat` module):
731
732 * ``UF_NODUMP``
733 * ``UF_IMMUTABLE``
734 * ``UF_APPEND``
735 * ``UF_OPAQUE``
736 * ``UF_NOUNLINK``
737 * ``SF_ARCHIVED``
738 * ``SF_IMMUTABLE``
739 * ``SF_APPEND``
740 * ``SF_NOUNLINK``
741 * ``SF_SNAPSHOT``
742
743 Availability: Macintosh, Unix.
744
Georg Brandl116aa622007-08-15 14:28:22 +0000745
746.. function:: chroot(path)
747
748 Change the root directory of the current process to *path*. Availability:
749 Macintosh, Unix.
750
Georg Brandl116aa622007-08-15 14:28:22 +0000751
752.. function:: chmod(path, mode)
753
754 Change the mode of *path* to the numeric *mode*. *mode* may take one of the
755 following values (as defined in the :mod:`stat` module) or bitwise or-ed
756 combinations of them:
757
758 * ``stat.S_ISUID``
759 * ``stat.S_ISGID``
760 * ``stat.S_ENFMT``
761 * ``stat.S_ISVTX``
762 * ``stat.S_IREAD``
763 * ``stat.S_IWRITE``
764 * ``stat.S_IEXEC``
765 * ``stat.S_IRWXU``
766 * ``stat.S_IRUSR``
767 * ``stat.S_IWUSR``
768 * ``stat.S_IXUSR``
769 * ``stat.S_IRWXG``
770 * ``stat.S_IRGRP``
771 * ``stat.S_IWGRP``
772 * ``stat.S_IXGRP``
773 * ``stat.S_IRWXO``
774 * ``stat.S_IROTH``
775 * ``stat.S_IWOTH``
776 * ``stat.S_IXOTH``
777
778 Availability: Macintosh, Unix, Windows.
779
780 .. note::
781
782 Although Windows supports :func:`chmod`, you can only set the file's read-only
783 flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD``
784 constants or a corresponding integer value). All other bits are
785 ignored.
786
787
788.. function:: chown(path, uid, gid)
789
790 Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave
791 one of the ids unchanged, set it to -1. Availability: Macintosh, Unix.
792
793
794.. function:: lchflags(path, flags)
795
796 Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not
797 follow symbolic links. Availability: Unix.
798
Georg Brandl116aa622007-08-15 14:28:22 +0000799
Christian Heimes93852662007-12-01 12:22:32 +0000800.. function:: lchmod(path, mode)
801
802 Change the mode of *path* to the numeric *mode*. If path is a symlink, this
803 affects the symlink rather than the target. See the docs for :func:`chmod`
804 for possible values of *mode*. Availability: Unix.
805
806 .. versionadded:: 2.6
807
808
Georg Brandl116aa622007-08-15 14:28:22 +0000809.. function:: lchown(path, uid, gid)
810
811 Change the owner and group id of *path* to the numeric *uid* and gid. This
812 function will not follow symbolic links. Availability: Macintosh, Unix.
813
Georg Brandl116aa622007-08-15 14:28:22 +0000814
815.. function:: link(src, dst)
816
817 Create a hard link pointing to *src* named *dst*. Availability: Macintosh, Unix.
818
819
820.. function:: listdir(path)
821
822 Return a list containing the names of the entries in the directory. The list is
823 in arbitrary order. It does not include the special entries ``'.'`` and
824 ``'..'`` even if they are present in the directory. Availability: Macintosh,
825 Unix, Windows.
826
Georg Brandl55ac8f02007-09-01 13:51:09 +0000827 On Windows NT/2k/XP and Unix, if *path* is a Unicode object, the result will be
828 a list of Unicode objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000829
830
831.. function:: lstat(path)
832
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000833 Like :func:`stat`, but do not follow symbolic links. This is an alias for
834 :func:`stat` on platforms that do not support symbolic links, such as
835 Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000836
837
838.. function:: mkfifo(path[, mode])
839
840 Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The default
841 *mode* is ``0666`` (octal). The current umask value is first masked out from
842 the mode. Availability: Macintosh, Unix.
843
844 FIFOs are pipes that can be accessed like regular files. FIFOs exist until they
845 are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
846 rendezvous between "client" and "server" type processes: the server opens the
847 FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo`
848 doesn't open the FIFO --- it just creates the rendezvous point.
849
850
851.. function:: mknod(filename[, mode=0600, device])
852
853 Create a filesystem node (file, device special file or named pipe) named
854 *filename*. *mode* specifies both the permissions to use and the type of node to
855 be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
856 ``stat.S_IFCHR``, ``stat.S_IFBLK``,
857 and ``stat.S_IFIFO`` (those constants are available in :mod:`stat`).
858 For ``stat.S_IFCHR`` and
859 ``stat.S_IFBLK``, *device* defines the newly created device special file (probably using
860 :func:`os.makedev`), otherwise it is ignored.
861
Georg Brandl116aa622007-08-15 14:28:22 +0000862
863.. function:: major(device)
864
865 Extracts the device major number from a raw device number (usually the
866 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
867
Georg Brandl116aa622007-08-15 14:28:22 +0000868
869.. function:: minor(device)
870
871 Extracts the device minor number from a raw device number (usually the
872 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
873
Georg Brandl116aa622007-08-15 14:28:22 +0000874
875.. function:: makedev(major, minor)
876
877 Composes a raw device number from the major and minor device numbers.
878
Georg Brandl116aa622007-08-15 14:28:22 +0000879
880.. function:: mkdir(path[, mode])
881
882 Create a directory named *path* with numeric mode *mode*. The default *mode* is
883 ``0777`` (octal). On some systems, *mode* is ignored. Where it is used, the
884 current umask value is first masked out. Availability: Macintosh, Unix, Windows.
885
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000886 It is also possible to create temporary directories; see the
887 :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
888
Georg Brandl116aa622007-08-15 14:28:22 +0000889
890.. function:: makedirs(path[, mode])
891
892 .. index::
893 single: directory; creating
894 single: UNC paths; and os.makedirs()
895
896 Recursive directory creation function. Like :func:`mkdir`, but makes all
897 intermediate-level directories needed to contain the leaf directory. Throws an
898 :exc:`error` exception if the leaf directory already exists or cannot be
899 created. The default *mode* is ``0777`` (octal). On some systems, *mode* is
900 ignored. Where it is used, the current umask value is first masked out.
901
902 .. note::
903
904 :func:`makedirs` will become confused if the path elements to create include
905 *os.pardir*.
906
Georg Brandl55ac8f02007-09-01 13:51:09 +0000907 This function handles UNC paths correctly.
Georg Brandl116aa622007-08-15 14:28:22 +0000908
909
910.. function:: pathconf(path, name)
911
912 Return system configuration information relevant to a named file. *name*
913 specifies the configuration value to retrieve; it may be a string which is the
914 name of a defined system value; these names are specified in a number of
915 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
916 additional names as well. The names known to the host operating system are
917 given in the ``pathconf_names`` dictionary. For configuration variables not
918 included in that mapping, passing an integer for *name* is also accepted.
919 Availability: Macintosh, Unix.
920
921 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
922 specific value for *name* is not supported by the host system, even if it is
923 included in ``pathconf_names``, an :exc:`OSError` is raised with
924 :const:`errno.EINVAL` for the error number.
925
926
927.. data:: pathconf_names
928
929 Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
930 the integer values defined for those names by the host operating system. This
931 can be used to determine the set of names known to the system. Availability:
932 Macintosh, Unix.
933
934
935.. function:: readlink(path)
936
937 Return a string representing the path to which the symbolic link points. The
938 result may be either an absolute or relative pathname; if it is relative, it may
939 be converted to an absolute pathname using ``os.path.join(os.path.dirname(path),
940 result)``.
941
Georg Brandl55ac8f02007-09-01 13:51:09 +0000942 If the *path* is a Unicode object, the result will also be a Unicode object.
Georg Brandl116aa622007-08-15 14:28:22 +0000943
944 Availability: Macintosh, Unix.
945
946
947.. function:: remove(path)
948
949 Remove the file *path*. If *path* is a directory, :exc:`OSError` is raised; see
950 :func:`rmdir` below to remove a directory. This is identical to the
951 :func:`unlink` function documented below. On Windows, attempting to remove a
952 file that is in use causes an exception to be raised; on Unix, the directory
953 entry is removed but the storage allocated to the file is not made available
954 until the original file is no longer in use. Availability: Macintosh, Unix,
955 Windows.
956
957
958.. function:: removedirs(path)
959
960 .. index:: single: directory; deleting
961
962 Removes directories recursively. Works like :func:`rmdir` except that, if the
963 leaf directory is successfully removed, :func:`removedirs` tries to
964 successively remove every parent directory mentioned in *path* until an error
965 is raised (which is ignored, because it generally means that a parent directory
966 is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
967 the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
968 they are empty. Raises :exc:`OSError` if the leaf directory could not be
969 successfully removed.
970
Georg Brandl116aa622007-08-15 14:28:22 +0000971
972.. function:: rename(src, dst)
973
974 Rename the file or directory *src* to *dst*. If *dst* is a directory,
975 :exc:`OSError` will be raised. On Unix, if *dst* exists and is a file, it will
976 be removed silently if the user has permission. The operation may fail on some
977 Unix flavors if *src* and *dst* are on different filesystems. If successful,
978 the renaming will be an atomic operation (this is a POSIX requirement). On
979 Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a
980 file; there may be no way to implement an atomic rename when *dst* names an
981 existing file. Availability: Macintosh, Unix, Windows.
982
983
984.. function:: renames(old, new)
985
986 Recursive directory or file renaming function. Works like :func:`rename`, except
987 creation of any intermediate directories needed to make the new pathname good is
988 attempted first. After the rename, directories corresponding to rightmost path
989 segments of the old name will be pruned away using :func:`removedirs`.
990
Georg Brandl116aa622007-08-15 14:28:22 +0000991 .. note::
992
993 This function can fail with the new directory structure made if you lack
994 permissions needed to remove the leaf directory or file.
995
996
997.. function:: rmdir(path)
998
999 Remove the directory *path*. Availability: Macintosh, Unix, Windows.
1000
1001
1002.. function:: stat(path)
1003
1004 Perform a :cfunc:`stat` system call on the given path. The return value is an
1005 object whose attributes correspond to the members of the :ctype:`stat`
1006 structure, namely: :attr:`st_mode` (protection bits), :attr:`st_ino` (inode
1007 number), :attr:`st_dev` (device), :attr:`st_nlink` (number of hard links),
1008 :attr:`st_uid` (user ID of owner), :attr:`st_gid` (group ID of owner),
1009 :attr:`st_size` (size of file, in bytes), :attr:`st_atime` (time of most recent
1010 access), :attr:`st_mtime` (time of most recent content modification),
1011 :attr:`st_ctime` (platform dependent; time of most recent metadata change on
1012 Unix, or the time of creation on Windows)::
1013
1014 >>> import os
1015 >>> statinfo = os.stat('somefile.txt')
1016 >>> statinfo
1017 (33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
1018 >>> statinfo.st_size
1019 926L
1020 >>>
1021
Georg Brandl55ac8f02007-09-01 13:51:09 +00001022 If :func:`stat_float_times` returns true, the time values are floats, measuring
1023 seconds. Fractions of a second may be reported if the system supports that. On
1024 Mac OS, the times are always floats. See :func:`stat_float_times` for further
1025 discussion.
Georg Brandl116aa622007-08-15 14:28:22 +00001026
1027 On some Unix systems (such as Linux), the following attributes may also be
1028 available: :attr:`st_blocks` (number of blocks allocated for file),
1029 :attr:`st_blksize` (filesystem blocksize), :attr:`st_rdev` (type of device if an
1030 inode device). :attr:`st_flags` (user defined flags for file).
1031
1032 On other Unix systems (such as FreeBSD), the following attributes may be
1033 available (but may be only filled out if root tries to use them): :attr:`st_gen`
1034 (file generation number), :attr:`st_birthtime` (time of file creation).
1035
1036 On Mac OS systems, the following attributes may also be available:
1037 :attr:`st_rsize`, :attr:`st_creator`, :attr:`st_type`.
1038
Georg Brandl116aa622007-08-15 14:28:22 +00001039 .. index:: module: stat
1040
1041 For backward compatibility, the return value of :func:`stat` is also accessible
1042 as a tuple of at least 10 integers giving the most important (and portable)
1043 members of the :ctype:`stat` structure, in the order :attr:`st_mode`,
1044 :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, :attr:`st_uid`,
1045 :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, :attr:`st_mtime`,
1046 :attr:`st_ctime`. More items may be added at the end by some implementations.
1047 The standard module :mod:`stat` defines functions and constants that are useful
1048 for extracting information from a :ctype:`stat` structure. (On Windows, some
1049 items are filled with dummy values.)
1050
1051 .. note::
1052
1053 The exact meaning and resolution of the :attr:`st_atime`, :attr:`st_mtime`, and
1054 :attr:`st_ctime` members depends on the operating system and the file system.
1055 For example, on Windows systems using the FAT or FAT32 file systems,
1056 :attr:`st_mtime` has 2-second resolution, and :attr:`st_atime` has only 1-day
1057 resolution. See your operating system documentation for details.
1058
1059 Availability: Macintosh, Unix, Windows.
1060
Georg Brandl116aa622007-08-15 14:28:22 +00001061
1062.. function:: stat_float_times([newvalue])
1063
1064 Determine whether :class:`stat_result` represents time stamps as float objects.
1065 If *newvalue* is ``True``, future calls to :func:`stat` return floats, if it is
1066 ``False``, future calls return ints. If *newvalue* is omitted, return the
1067 current setting.
1068
1069 For compatibility with older Python versions, accessing :class:`stat_result` as
1070 a tuple always returns integers.
1071
Georg Brandl55ac8f02007-09-01 13:51:09 +00001072 Python now returns float values by default. Applications which do not work
1073 correctly with floating point time stamps can use this function to restore the
1074 old behaviour.
Georg Brandl116aa622007-08-15 14:28:22 +00001075
1076 The resolution of the timestamps (that is the smallest possible fraction)
1077 depends on the system. Some systems only support second resolution; on these
1078 systems, the fraction will always be zero.
1079
1080 It is recommended that this setting is only changed at program startup time in
1081 the *__main__* module; libraries should never change this setting. If an
1082 application uses a library that works incorrectly if floating point time stamps
1083 are processed, this application should turn the feature off until the library
1084 has been corrected.
1085
1086
1087.. function:: statvfs(path)
1088
1089 Perform a :cfunc:`statvfs` system call on the given path. The return value is
1090 an object whose attributes describe the filesystem on the given path, and
1091 correspond to the members of the :ctype:`statvfs` structure, namely:
1092 :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
1093 :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
1094 :attr:`f_flag`, :attr:`f_namemax`. Availability: Unix.
1095
1096 .. index:: module: statvfs
1097
1098 For backward compatibility, the return value is also accessible as a tuple whose
1099 values correspond to the attributes, in the order given above. The standard
1100 module :mod:`statvfs` defines constants that are useful for extracting
1101 information from a :ctype:`statvfs` structure when accessing it as a sequence;
1102 this remains useful when writing code that needs to work with versions of Python
1103 that don't support accessing the fields as attributes.
1104
Georg Brandl116aa622007-08-15 14:28:22 +00001105
1106.. function:: symlink(src, dst)
1107
1108 Create a symbolic link pointing to *src* named *dst*. Availability: Unix.
1109
1110
Georg Brandl116aa622007-08-15 14:28:22 +00001111.. function:: unlink(path)
1112
1113 Remove the file *path*. This is the same function as :func:`remove`; the
1114 :func:`unlink` name is its traditional Unix name. Availability: Macintosh, Unix,
1115 Windows.
1116
1117
1118.. function:: utime(path, times)
1119
1120 Set the access and modified times of the file specified by *path*. If *times* is
1121 ``None``, then the file's access and modified times are set to the current time.
1122 Otherwise, *times* must be a 2-tuple of numbers, of the form ``(atime, mtime)``
1123 which is used to set the access and modified times, respectively. Whether a
1124 directory can be given for *path* depends on whether the operating system
1125 implements directories as files (for example, Windows does not). Note that the
1126 exact times you set here may not be returned by a subsequent :func:`stat` call,
1127 depending on the resolution with which your operating system records access and
1128 modification times; see :func:`stat`.
1129
Georg Brandl116aa622007-08-15 14:28:22 +00001130 Availability: Macintosh, Unix, Windows.
1131
1132
1133.. function:: walk(top[, topdown=True [, onerror=None[, followlinks=False]]])
1134
1135 .. index::
1136 single: directory; walking
1137 single: directory; traversal
1138
1139 :func:`walk` generates the file names in a directory tree, by walking the tree
1140 either top down or bottom up. For each directory in the tree rooted at directory
1141 *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
1142 filenames)``.
1143
1144 *dirpath* is a string, the path to the directory. *dirnames* is a list of the
1145 names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``).
1146 *filenames* is a list of the names of the non-directory files in *dirpath*.
1147 Note that the names in the lists contain no path components. To get a full path
1148 (which begins with *top*) to a file or directory in *dirpath*, do
1149 ``os.path.join(dirpath, name)``.
1150
1151 If optional argument *topdown* is true or not specified, the triple for a
1152 directory is generated before the triples for any of its subdirectories
1153 (directories are generated top down). If *topdown* is false, the triple for a
1154 directory is generated after the triples for all of its subdirectories
1155 (directories are generated bottom up).
1156
1157 When *topdown* is true, the caller can modify the *dirnames* list in-place
1158 (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
1159 recurse into the subdirectories whose names remain in *dirnames*; this can be
1160 used to prune the search, impose a specific order of visiting, or even to inform
1161 :func:`walk` about directories the caller creates or renames before it resumes
1162 :func:`walk` again. Modifying *dirnames* when *topdown* is false is
1163 ineffective, because in bottom-up mode the directories in *dirnames* are
1164 generated before *dirpath* itself is generated.
1165
1166 By default errors from the ``os.listdir()`` call are ignored. If optional
1167 argument *onerror* is specified, it should be a function; it will be called with
1168 one argument, an :exc:`OSError` instance. It can report the error to continue
1169 with the walk, or raise the exception to abort the walk. Note that the filename
1170 is available as the ``filename`` attribute of the exception object.
1171
1172 By default, :func:`walk` will not walk down into symbolic links that resolve to
1173 directories. Set *followlinks* to True to visit directories pointed to by
1174 symlinks, on systems that support them.
1175
Georg Brandl116aa622007-08-15 14:28:22 +00001176 .. note::
1177
1178 Be aware that setting *followlinks* to true can lead to infinite recursion if a
1179 link points to a parent directory of itself. :func:`walk` does not keep track of
1180 the directories it visited already.
1181
1182 .. note::
1183
1184 If you pass a relative pathname, don't change the current working directory
1185 between resumptions of :func:`walk`. :func:`walk` never changes the current
1186 directory, and assumes that its caller doesn't either.
1187
1188 This example displays the number of bytes taken by non-directory files in each
1189 directory under the starting directory, except that it doesn't look under any
1190 CVS subdirectory::
1191
1192 import os
1193 from os.path import join, getsize
1194 for root, dirs, files in os.walk('python/Lib/email'):
Georg Brandl6911e3c2007-09-04 07:15:32 +00001195 print(root, "consumes", end=" ")
1196 print(sum(getsize(join(root, name)) for name in files), end=" ")
1197 print("bytes in", len(files), "non-directory files")
Georg Brandl116aa622007-08-15 14:28:22 +00001198 if 'CVS' in dirs:
1199 dirs.remove('CVS') # don't visit CVS directories
1200
1201 In the next example, walking the tree bottom up is essential: :func:`rmdir`
1202 doesn't allow deleting a directory before the directory is empty::
1203
1204 # Delete everything reachable from the directory named in 'top',
1205 # assuming there are no symbolic links.
1206 # CAUTION: This is dangerous! For example, if top == '/', it
1207 # could delete all your disk files.
1208 import os
1209 for root, dirs, files in os.walk(top, topdown=False):
1210 for name in files:
1211 os.remove(os.path.join(root, name))
1212 for name in dirs:
1213 os.rmdir(os.path.join(root, name))
1214
Georg Brandl116aa622007-08-15 14:28:22 +00001215
1216.. _os-process:
1217
1218Process Management
1219------------------
1220
1221These functions may be used to create and manage processes.
1222
1223The various :func:`exec\*` functions take a list of arguments for the new
1224program loaded into the process. In each case, the first of these arguments is
1225passed to the new program as its own name rather than as an argument a user may
1226have typed on a command line. For the C programmer, this is the ``argv[0]``
1227passed to a program's :cfunc:`main`. For example, ``os.execv('/bin/echo',
1228['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
1229to be ignored.
1230
1231
1232.. function:: abort()
1233
1234 Generate a :const:`SIGABRT` signal to the current process. On Unix, the default
1235 behavior is to produce a core dump; on Windows, the process immediately returns
1236 an exit code of ``3``. Be aware that programs which use :func:`signal.signal`
1237 to register a handler for :const:`SIGABRT` will behave differently.
1238 Availability: Macintosh, Unix, Windows.
1239
1240
1241.. function:: execl(path, arg0, arg1, ...)
1242 execle(path, arg0, arg1, ..., env)
1243 execlp(file, arg0, arg1, ...)
1244 execlpe(file, arg0, arg1, ..., env)
1245 execv(path, args)
1246 execve(path, args, env)
1247 execvp(file, args)
1248 execvpe(file, args, env)
1249
1250 These functions all execute a new program, replacing the current process; they
1251 do not return. On Unix, the new executable is loaded into the current process,
1252 and will have the same process ID as the caller. Errors will be reported as
1253 :exc:`OSError` exceptions.
1254
1255 The ``'l'`` and ``'v'`` variants of the :func:`exec\*` functions differ in how
1256 command-line arguments are passed. The ``'l'`` variants are perhaps the easiest
1257 to work with if the number of parameters is fixed when the code is written; the
1258 individual parameters simply become additional parameters to the :func:`execl\*`
1259 functions. The ``'v'`` variants are good when the number of parameters is
1260 variable, with the arguments being passed in a list or tuple as the *args*
1261 parameter. In either case, the arguments to the child process should start with
1262 the name of the command being run, but this is not enforced.
1263
1264 The variants which include a ``'p'`` near the end (:func:`execlp`,
1265 :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
1266 :envvar:`PATH` environment variable to locate the program *file*. When the
1267 environment is being replaced (using one of the :func:`exec\*e` variants,
1268 discussed in the next paragraph), the new environment is used as the source of
1269 the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
1270 :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
1271 locate the executable; *path* must contain an appropriate absolute or relative
1272 path.
1273
1274 For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
1275 that these all end in ``'e'``), the *env* parameter must be a mapping which is
1276 used to define the environment variables for the new process; the :func:`execl`,
1277 :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
1278 inherit the environment of the current process. Availability: Macintosh, Unix,
1279 Windows.
1280
1281
1282.. function:: _exit(n)
1283
1284 Exit to the system with status *n*, without calling cleanup handlers, flushing
1285 stdio buffers, etc. Availability: Macintosh, Unix, Windows.
1286
1287 .. note::
1288
1289 The standard way to exit is ``sys.exit(n)``. :func:`_exit` should normally only
1290 be used in the child process after a :func:`fork`.
1291
1292The following exit codes are a defined, and can be used with :func:`_exit`,
1293although they are not required. These are typically used for system programs
1294written in Python, such as a mail server's external command delivery program.
1295
1296.. note::
1297
1298 Some of these may not be available on all Unix platforms, since there is some
1299 variation. These constants are defined where they are defined by the underlying
1300 platform.
1301
1302
1303.. data:: EX_OK
1304
1305 Exit code that means no error occurred. Availability: Macintosh, Unix.
1306
Georg Brandl116aa622007-08-15 14:28:22 +00001307
1308.. data:: EX_USAGE
1309
1310 Exit code that means the command was used incorrectly, such as when the wrong
1311 number of arguments are given. Availability: Macintosh, Unix.
1312
Georg Brandl116aa622007-08-15 14:28:22 +00001313
1314.. data:: EX_DATAERR
1315
1316 Exit code that means the input data was incorrect. Availability: Macintosh,
1317 Unix.
1318
Georg Brandl116aa622007-08-15 14:28:22 +00001319
1320.. data:: EX_NOINPUT
1321
1322 Exit code that means an input file did not exist or was not readable.
1323 Availability: Macintosh, Unix.
1324
Georg Brandl116aa622007-08-15 14:28:22 +00001325
1326.. data:: EX_NOUSER
1327
1328 Exit code that means a specified user did not exist. Availability: Macintosh,
1329 Unix.
1330
Georg Brandl116aa622007-08-15 14:28:22 +00001331
1332.. data:: EX_NOHOST
1333
1334 Exit code that means a specified host did not exist. Availability: Macintosh,
1335 Unix.
1336
Georg Brandl116aa622007-08-15 14:28:22 +00001337
1338.. data:: EX_UNAVAILABLE
1339
1340 Exit code that means that a required service is unavailable. Availability:
1341 Macintosh, Unix.
1342
Georg Brandl116aa622007-08-15 14:28:22 +00001343
1344.. data:: EX_SOFTWARE
1345
1346 Exit code that means an internal software error was detected. Availability:
1347 Macintosh, Unix.
1348
Georg Brandl116aa622007-08-15 14:28:22 +00001349
1350.. data:: EX_OSERR
1351
1352 Exit code that means an operating system error was detected, such as the
1353 inability to fork or create a pipe. Availability: Macintosh, Unix.
1354
Georg Brandl116aa622007-08-15 14:28:22 +00001355
1356.. data:: EX_OSFILE
1357
1358 Exit code that means some system file did not exist, could not be opened, or had
1359 some other kind of error. Availability: Macintosh, Unix.
1360
Georg Brandl116aa622007-08-15 14:28:22 +00001361
1362.. data:: EX_CANTCREAT
1363
1364 Exit code that means a user specified output file could not be created.
1365 Availability: Macintosh, Unix.
1366
Georg Brandl116aa622007-08-15 14:28:22 +00001367
1368.. data:: EX_IOERR
1369
1370 Exit code that means that an error occurred while doing I/O on some file.
1371 Availability: Macintosh, Unix.
1372
Georg Brandl116aa622007-08-15 14:28:22 +00001373
1374.. data:: EX_TEMPFAIL
1375
1376 Exit code that means a temporary failure occurred. This indicates something
1377 that may not really be an error, such as a network connection that couldn't be
1378 made during a retryable operation. Availability: Macintosh, Unix.
1379
Georg Brandl116aa622007-08-15 14:28:22 +00001380
1381.. data:: EX_PROTOCOL
1382
1383 Exit code that means that a protocol exchange was illegal, invalid, or not
1384 understood. Availability: Macintosh, Unix.
1385
Georg Brandl116aa622007-08-15 14:28:22 +00001386
1387.. data:: EX_NOPERM
1388
1389 Exit code that means that there were insufficient permissions to perform the
1390 operation (but not intended for file system problems). Availability: Macintosh,
1391 Unix.
1392
Georg Brandl116aa622007-08-15 14:28:22 +00001393
1394.. data:: EX_CONFIG
1395
1396 Exit code that means that some kind of configuration error occurred.
1397 Availability: Macintosh, Unix.
1398
Georg Brandl116aa622007-08-15 14:28:22 +00001399
1400.. data:: EX_NOTFOUND
1401
1402 Exit code that means something like "an entry was not found". Availability:
1403 Macintosh, Unix.
1404
Georg Brandl116aa622007-08-15 14:28:22 +00001405
1406.. function:: fork()
1407
1408 Fork a child process. Return ``0`` in the child, the child's process id in the
1409 parent. Availability: Macintosh, Unix.
1410
1411
1412.. function:: forkpty()
1413
1414 Fork a child process, using a new pseudo-terminal as the child's controlling
1415 terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
1416 new child's process id in the parent, and *fd* is the file descriptor of the
1417 master end of the pseudo-terminal. For a more portable approach, use the
1418 :mod:`pty` module. Availability: Macintosh, Some flavors of Unix.
1419
1420
1421.. function:: kill(pid, sig)
1422
1423 .. index::
1424 single: process; killing
1425 single: process; signalling
1426
1427 Send signal *sig* to the process *pid*. Constants for the specific signals
1428 available on the host platform are defined in the :mod:`signal` module.
1429 Availability: Macintosh, Unix.
1430
1431
1432.. function:: killpg(pgid, sig)
1433
1434 .. index::
1435 single: process; killing
1436 single: process; signalling
1437
1438 Send the signal *sig* to the process group *pgid*. Availability: Macintosh,
1439 Unix.
1440
Georg Brandl116aa622007-08-15 14:28:22 +00001441
1442.. function:: nice(increment)
1443
1444 Add *increment* to the process's "niceness". Return the new niceness.
1445 Availability: Macintosh, Unix.
1446
1447
1448.. function:: plock(op)
1449
1450 Lock program segments into memory. The value of *op* (defined in
1451 ``<sys/lock.h>``) determines which segments are locked. Availability: Macintosh,
1452 Unix.
1453
1454
1455.. function:: popen(...)
1456 :noindex:
1457
1458 Run child processes, returning opened pipes for communications. These functions
1459 are described in section :ref:`os-newstreams`.
1460
1461
1462.. function:: spawnl(mode, path, ...)
1463 spawnle(mode, path, ..., env)
1464 spawnlp(mode, file, ...)
1465 spawnlpe(mode, file, ..., env)
1466 spawnv(mode, path, args)
1467 spawnve(mode, path, args, env)
1468 spawnvp(mode, file, args)
1469 spawnvpe(mode, file, args, env)
1470
1471 Execute the program *path* in a new process.
1472
1473 (Note that the :mod:`subprocess` module provides more powerful facilities for
1474 spawning new processes and retrieving their results; using that module is
1475 preferable to using these functions.)
1476
1477 If *mode* is :const:`P_NOWAIT`, this function returns the process ID of the new
1478 process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
1479 exits normally, or ``-signal``, where *signal* is the signal that killed the
1480 process. On Windows, the process ID will actually be the process handle, so can
1481 be used with the :func:`waitpid` function.
1482
1483 The ``'l'`` and ``'v'`` variants of the :func:`spawn\*` functions differ in how
1484 command-line arguments are passed. The ``'l'`` variants are perhaps the easiest
1485 to work with if the number of parameters is fixed when the code is written; the
1486 individual parameters simply become additional parameters to the
1487 :func:`spawnl\*` functions. The ``'v'`` variants are good when the number of
1488 parameters is variable, with the arguments being passed in a list or tuple as
1489 the *args* parameter. In either case, the arguments to the child process must
1490 start with the name of the command being run.
1491
1492 The variants which include a second ``'p'`` near the end (:func:`spawnlp`,
1493 :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
1494 :envvar:`PATH` environment variable to locate the program *file*. When the
1495 environment is being replaced (using one of the :func:`spawn\*e` variants,
1496 discussed in the next paragraph), the new environment is used as the source of
1497 the :envvar:`PATH` variable. The other variants, :func:`spawnl`,
1498 :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
1499 :envvar:`PATH` variable to locate the executable; *path* must contain an
1500 appropriate absolute or relative path.
1501
1502 For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
1503 (note that these all end in ``'e'``), the *env* parameter must be a mapping
1504 which is used to define the environment variables for the new process; the
1505 :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
1506 the new process to inherit the environment of the current process.
1507
1508 As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are
1509 equivalent::
1510
1511 import os
1512 os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
1513
1514 L = ['cp', 'index.html', '/dev/null']
1515 os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
1516
1517 Availability: Unix, Windows. :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
1518 and :func:`spawnvpe` are not available on Windows.
1519
Georg Brandl116aa622007-08-15 14:28:22 +00001520
1521.. data:: P_NOWAIT
1522 P_NOWAITO
1523
1524 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1525 functions. If either of these values is given, the :func:`spawn\*` functions
1526 will return as soon as the new process has been created, with the process ID as
1527 the return value. Availability: Macintosh, Unix, Windows.
1528
Georg Brandl116aa622007-08-15 14:28:22 +00001529
1530.. data:: P_WAIT
1531
1532 Possible value for the *mode* parameter to the :func:`spawn\*` family of
1533 functions. If this is given as *mode*, the :func:`spawn\*` functions will not
1534 return until the new process has run to completion and will return the exit code
1535 of the process the run is successful, or ``-signal`` if a signal kills the
1536 process. Availability: Macintosh, Unix, Windows.
1537
Georg Brandl116aa622007-08-15 14:28:22 +00001538
1539.. data:: P_DETACH
1540 P_OVERLAY
1541
1542 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1543 functions. These are less portable than those listed above. :const:`P_DETACH`
1544 is similar to :const:`P_NOWAIT`, but the new process is detached from the
1545 console of the calling process. If :const:`P_OVERLAY` is used, the current
1546 process will be replaced; the :func:`spawn\*` function will not return.
1547 Availability: Windows.
1548
Georg Brandl116aa622007-08-15 14:28:22 +00001549
1550.. function:: startfile(path[, operation])
1551
1552 Start a file with its associated application.
1553
1554 When *operation* is not specified or ``'open'``, this acts like double-clicking
1555 the file in Windows Explorer, or giving the file name as an argument to the
1556 :program:`start` command from the interactive command shell: the file is opened
1557 with whatever application (if any) its extension is associated.
1558
1559 When another *operation* is given, it must be a "command verb" that specifies
1560 what should be done with the file. Common verbs documented by Microsoft are
1561 ``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` and
1562 ``'find'`` (to be used on directories).
1563
1564 :func:`startfile` returns as soon as the associated application is launched.
1565 There is no option to wait for the application to close, and no way to retrieve
1566 the application's exit status. The *path* parameter is relative to the current
1567 directory. If you want to use an absolute path, make sure the first character
1568 is not a slash (``'/'``); the underlying Win32 :cfunc:`ShellExecute` function
1569 doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that
1570 the path is properly encoded for Win32. Availability: Windows.
1571
Georg Brandl116aa622007-08-15 14:28:22 +00001572
1573.. function:: system(command)
1574
1575 Execute the command (a string) in a subshell. This is implemented by calling
1576 the Standard C function :cfunc:`system`, and has the same limitations. Changes
1577 to ``posix.environ``, ``sys.stdin``, etc. are not reflected in the environment
1578 of the executed command.
1579
1580 On Unix, the return value is the exit status of the process encoded in the
1581 format specified for :func:`wait`. Note that POSIX does not specify the meaning
1582 of the return value of the C :cfunc:`system` function, so the return value of
1583 the Python function is system-dependent.
1584
1585 On Windows, the return value is that returned by the system shell after running
1586 *command*, given by the Windows environment variable :envvar:`COMSPEC`: on
1587 :program:`command.com` systems (Windows 95, 98 and ME) this is always ``0``; on
1588 :program:`cmd.exe` systems (Windows NT, 2000 and XP) this is the exit status of
1589 the command run; on systems using a non-native shell, consult your shell
1590 documentation.
1591
1592 Availability: Macintosh, Unix, Windows.
1593
1594 The :mod:`subprocess` module provides more powerful facilities for spawning new
1595 processes and retrieving their results; using that module is preferable to using
1596 this function.
1597
1598
1599.. function:: times()
1600
1601 Return a 5-tuple of floating point numbers indicating accumulated (processor or
1602 other) times, in seconds. The items are: user time, system time, children's
1603 user time, children's system time, and elapsed real time since a fixed point in
1604 the past, in that order. See the Unix manual page :manpage:`times(2)` or the
1605 corresponding Windows Platform API documentation. Availability: Macintosh, Unix,
1606 Windows.
1607
1608
1609.. function:: wait()
1610
1611 Wait for completion of a child process, and return a tuple containing its pid
1612 and exit status indication: a 16-bit number, whose low byte is the signal number
1613 that killed the process, and whose high byte is the exit status (if the signal
1614 number is zero); the high bit of the low byte is set if a core file was
1615 produced. Availability: Macintosh, Unix.
1616
1617
1618.. function:: waitpid(pid, options)
1619
1620 The details of this function differ on Unix and Windows.
1621
1622 On Unix: Wait for completion of a child process given by process id *pid*, and
1623 return a tuple containing its process id and exit status indication (encoded as
1624 for :func:`wait`). The semantics of the call are affected by the value of the
1625 integer *options*, which should be ``0`` for normal operation.
1626
1627 If *pid* is greater than ``0``, :func:`waitpid` requests status information for
1628 that specific process. If *pid* is ``0``, the request is for the status of any
1629 child in the process group of the current process. If *pid* is ``-1``, the
1630 request pertains to any child of the current process. If *pid* is less than
1631 ``-1``, status is requested for any process in the process group ``-pid`` (the
1632 absolute value of *pid*).
1633
1634 On Windows: Wait for completion of a process given by process handle *pid*, and
1635 return a tuple containing *pid*, and its exit status shifted left by 8 bits
1636 (shifting makes cross-platform use of the function easier). A *pid* less than or
1637 equal to ``0`` has no special meaning on Windows, and raises an exception. The
1638 value of integer *options* has no effect. *pid* can refer to any process whose
1639 id is known, not necessarily a child process. The :func:`spawn` functions called
1640 with :const:`P_NOWAIT` return suitable process handles.
1641
1642
1643.. function:: wait3([options])
1644
1645 Similar to :func:`waitpid`, except no process id argument is given and a
1646 3-element tuple containing the child's process id, exit status indication, and
1647 resource usage information is returned. Refer to :mod:`resource`.\
1648 :func:`getrusage` for details on resource usage information. The option
1649 argument is the same as that provided to :func:`waitpid` and :func:`wait4`.
1650 Availability: Unix.
1651
Georg Brandl116aa622007-08-15 14:28:22 +00001652
1653.. function:: wait4(pid, options)
1654
1655 Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
1656 process id, exit status indication, and resource usage information is returned.
1657 Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage
1658 information. The arguments to :func:`wait4` are the same as those provided to
1659 :func:`waitpid`. Availability: Unix.
1660
Georg Brandl116aa622007-08-15 14:28:22 +00001661
1662.. data:: WNOHANG
1663
1664 The option for :func:`waitpid` to return immediately if no child process status
1665 is available immediately. The function returns ``(0, 0)`` in this case.
1666 Availability: Macintosh, Unix.
1667
1668
1669.. data:: WCONTINUED
1670
1671 This option causes child processes to be reported if they have been continued
1672 from a job control stop since their status was last reported. Availability: Some
1673 Unix systems.
1674
Georg Brandl116aa622007-08-15 14:28:22 +00001675
1676.. data:: WUNTRACED
1677
1678 This option causes child processes to be reported if they have been stopped but
1679 their current state has not been reported since they were stopped. Availability:
1680 Macintosh, Unix.
1681
Georg Brandl116aa622007-08-15 14:28:22 +00001682
1683The following functions take a process status code as returned by
1684:func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be
1685used to determine the disposition of a process.
1686
Georg Brandl116aa622007-08-15 14:28:22 +00001687.. function:: WCOREDUMP(status)
1688
1689 Returns ``True`` if a core dump was generated for the process, otherwise it
1690 returns ``False``. Availability: Macintosh, Unix.
1691
Georg Brandl116aa622007-08-15 14:28:22 +00001692
1693.. function:: WIFCONTINUED(status)
1694
1695 Returns ``True`` if the process has been continued from a job control stop,
1696 otherwise it returns ``False``. Availability: Unix.
1697
Georg Brandl116aa622007-08-15 14:28:22 +00001698
1699.. function:: WIFSTOPPED(status)
1700
1701 Returns ``True`` if the process has been stopped, otherwise it returns
1702 ``False``. Availability: Unix.
1703
1704
1705.. function:: WIFSIGNALED(status)
1706
1707 Returns ``True`` if the process exited due to a signal, otherwise it returns
1708 ``False``. Availability: Macintosh, Unix.
1709
1710
1711.. function:: WIFEXITED(status)
1712
1713 Returns ``True`` if the process exited using the :manpage:`exit(2)` system call,
1714 otherwise it returns ``False``. Availability: Macintosh, Unix.
1715
1716
1717.. function:: WEXITSTATUS(status)
1718
1719 If ``WIFEXITED(status)`` is true, return the integer parameter to the
1720 :manpage:`exit(2)` system call. Otherwise, the return value is meaningless.
1721 Availability: Macintosh, Unix.
1722
1723
1724.. function:: WSTOPSIG(status)
1725
1726 Return the signal which caused the process to stop. Availability: Macintosh,
1727 Unix.
1728
1729
1730.. function:: WTERMSIG(status)
1731
1732 Return the signal which caused the process to exit. Availability: Macintosh,
1733 Unix.
1734
1735
1736.. _os-path:
1737
1738Miscellaneous System Information
1739--------------------------------
1740
1741
1742.. function:: confstr(name)
1743
1744 Return string-valued system configuration values. *name* specifies the
1745 configuration value to retrieve; it may be a string which is the name of a
1746 defined system value; these names are specified in a number of standards (POSIX,
1747 Unix 95, Unix 98, and others). Some platforms define additional names as well.
1748 The names known to the host operating system are given as the keys of the
1749 ``confstr_names`` dictionary. For configuration variables not included in that
1750 mapping, passing an integer for *name* is also accepted. Availability:
1751 Macintosh, Unix.
1752
1753 If the configuration value specified by *name* isn't defined, ``None`` is
1754 returned.
1755
1756 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
1757 specific value for *name* is not supported by the host system, even if it is
1758 included in ``confstr_names``, an :exc:`OSError` is raised with
1759 :const:`errno.EINVAL` for the error number.
1760
1761
1762.. data:: confstr_names
1763
1764 Dictionary mapping names accepted by :func:`confstr` to the integer values
1765 defined for those names by the host operating system. This can be used to
1766 determine the set of names known to the system. Availability: Macintosh, Unix.
1767
1768
1769.. function:: getloadavg()
1770
1771 Return the number of processes in the system run queue averaged over the last 1,
1772 5, and 15 minutes or raises :exc:`OSError` if the load average was
1773 unobtainable.
1774
Georg Brandl116aa622007-08-15 14:28:22 +00001775
1776.. function:: sysconf(name)
1777
1778 Return integer-valued system configuration values. If the configuration value
1779 specified by *name* isn't defined, ``-1`` is returned. The comments regarding
1780 the *name* parameter for :func:`confstr` apply here as well; the dictionary that
1781 provides information on the known names is given by ``sysconf_names``.
1782 Availability: Macintosh, Unix.
1783
1784
1785.. data:: sysconf_names
1786
1787 Dictionary mapping names accepted by :func:`sysconf` to the integer values
1788 defined for those names by the host operating system. This can be used to
1789 determine the set of names known to the system. Availability: Macintosh, Unix.
1790
1791The follow data values are used to support path manipulation operations. These
1792are defined for all platforms.
1793
1794Higher-level operations on pathnames are defined in the :mod:`os.path` module.
1795
1796
1797.. data:: curdir
1798
1799 The constant string used by the operating system to refer to the current
1800 directory. For example: ``'.'`` for POSIX or ``':'`` for Mac OS 9. Also
1801 available via :mod:`os.path`.
1802
1803
1804.. data:: pardir
1805
1806 The constant string used by the operating system to refer to the parent
1807 directory. For example: ``'..'`` for POSIX or ``'::'`` for Mac OS 9. Also
1808 available via :mod:`os.path`.
1809
1810
1811.. data:: sep
1812
1813 The character used by the operating system to separate pathname components, for
1814 example, ``'/'`` for POSIX or ``':'`` for Mac OS 9. Note that knowing this is
1815 not sufficient to be able to parse or concatenate pathnames --- use
1816 :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
1817 useful. Also available via :mod:`os.path`.
1818
1819
1820.. data:: altsep
1821
1822 An alternative character used by the operating system to separate pathname
1823 components, or ``None`` if only one separator character exists. This is set to
1824 ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
1825 :mod:`os.path`.
1826
1827
1828.. data:: extsep
1829
1830 The character which separates the base filename from the extension; for example,
1831 the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.
1832
Georg Brandl116aa622007-08-15 14:28:22 +00001833
1834.. data:: pathsep
1835
1836 The character conventionally used by the operating system to separate search
1837 path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
1838 Windows. Also available via :mod:`os.path`.
1839
1840
1841.. data:: defpath
1842
1843 The default search path used by :func:`exec\*p\*` and :func:`spawn\*p\*` if the
1844 environment doesn't have a ``'PATH'`` key. Also available via :mod:`os.path`.
1845
1846
1847.. data:: linesep
1848
1849 The string used to separate (or, rather, terminate) lines on the current
1850 platform. This may be a single character, such as ``'\n'`` for POSIX or
1851 ``'\r'`` for Mac OS, or multiple characters, for example, ``'\r\n'`` for
1852 Windows. Do not use *os.linesep* as a line terminator when writing files opened
1853 in text mode (the default); use a single ``'\n'`` instead, on all platforms.
1854
1855
1856.. data:: devnull
1857
1858 The file path of the null device. For example: ``'/dev/null'`` for POSIX or
1859 ``'Dev:Nul'`` for Mac OS 9. Also available via :mod:`os.path`.
1860
Georg Brandl116aa622007-08-15 14:28:22 +00001861
1862.. _os-miscfunc:
1863
1864Miscellaneous Functions
1865-----------------------
1866
1867
1868.. function:: urandom(n)
1869
1870 Return a string of *n* random bytes suitable for cryptographic use.
1871
1872 This function returns random bytes from an OS-specific randomness source. The
1873 returned data should be unpredictable enough for cryptographic applications,
1874 though its exact quality depends on the OS implementation. On a UNIX-like
1875 system this will query /dev/urandom, and on Windows it will use CryptGenRandom.
1876 If a randomness source is not found, :exc:`NotImplementedError` will be raised.