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