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