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