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