blob: 2a8325ab4ea66ea885b6de1d5c4189bbb92c4b0e [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
294.. % placed in this section since it relates to errno.... a little weak
295
296
297.. function:: strerror(code)
298
299 Return the error message corresponding to the error code in *code*.
300 Availability: Unix, Windows.
301
302
303.. function:: umask(mask)
304
305 Set the current numeric umask and returns the previous umask. Availability:
306 Unix, Windows.
307
308
309.. function:: uname()
310
311 .. index::
312 single: gethostname() (in module socket)
313 single: gethostbyaddr() (in module socket)
314
315 Return a 5-tuple containing information identifying the current operating
316 system. The tuple contains 5 strings: ``(sysname, nodename, release, version,
317 machine)``. Some systems truncate the nodename to 8 characters or to the
318 leading component; a better way to get the hostname is
319 :func:`socket.gethostname` or even
320 ``socket.gethostbyaddr(socket.gethostname())``. Availability: recent flavors of
321 Unix.
322
323
324.. function:: unsetenv(varname)
325
326 .. index:: single: environment variables; deleting
327
328 Unset (delete) the environment variable named *varname*. Such changes to the
329 environment affect subprocesses started with :func:`os.system`, :func:`popen` or
330 :func:`fork` and :func:`execv`. Availability: most flavors of Unix, Windows.
331
332 When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is
333 automatically translated into a corresponding call to :func:`unsetenv`; however,
334 calls to :func:`unsetenv` don't update ``os.environ``, so it is actually
335 preferable to delete items of ``os.environ``.
336
337
338.. _os-newstreams:
339
340File Object Creation
341--------------------
342
343These functions create new file objects. (See also :func:`open`.)
344
345
346.. function:: fdopen(fd[, mode[, bufsize]])
347
348 .. index:: single: I/O control; buffering
349
350 Return an open file object connected to the file descriptor *fd*. The *mode*
351 and *bufsize* arguments have the same meaning as the corresponding arguments to
352 the built-in :func:`open` function. Availability: Macintosh, Unix, Windows.
353
Georg Brandl55ac8f02007-09-01 13:51:09 +0000354 When specified, the *mode* argument must start with one of the letters
355 ``'r'``, ``'w'``, or ``'a'``, otherwise a :exc:`ValueError` is raised.
Georg Brandl116aa622007-08-15 14:28:22 +0000356
Georg Brandl55ac8f02007-09-01 13:51:09 +0000357 On Unix, when the *mode* argument starts with ``'a'``, the *O_APPEND* flag is
358 set on the file descriptor (which the :cfunc:`fdopen` implementation already
359 does on most platforms).
Georg Brandl116aa622007-08-15 14:28:22 +0000360
361
362.. function:: popen(command[, mode[, bufsize]])
363
364 Open a pipe to or from *command*. The return value is an open file object
365 connected to the pipe, which can be read or written depending on whether *mode*
366 is ``'r'`` (default) or ``'w'``. The *bufsize* argument has the same meaning as
367 the corresponding argument to the built-in :func:`open` function. The exit
368 status of the command (encoded in the format specified for :func:`wait`) is
369 available as the return value of the :meth:`close` method of the file object,
370 except that when the exit status is zero (termination without errors), ``None``
371 is returned. Availability: Macintosh, Unix, Windows.
372
373 .. deprecated:: 2.6
374 This function is obsolete. Use the :mod:`subprocess` module.
375
Georg Brandl116aa622007-08-15 14:28:22 +0000376
Georg Brandl116aa622007-08-15 14:28:22 +0000377.. _os-fd-ops:
378
379File Descriptor Operations
380--------------------------
381
382These functions operate on I/O streams referenced using file descriptors.
383
384File descriptors are small integers corresponding to a file that has been opened
385by the current process. For example, standard input is usually file descriptor
3860, standard output is 1, and standard error is 2. Further files opened by a
387process will then be assigned 3, 4, 5, and so forth. The name "file descriptor"
388is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
389by file descriptors.
390
391
392.. function:: close(fd)
393
394 Close file descriptor *fd*. Availability: Macintosh, Unix, Windows.
395
396 .. note::
397
398 This function is intended for low-level I/O and must be applied to a file
399 descriptor as returned by :func:`open` or :func:`pipe`. To close a "file
400 object" returned by the built-in function :func:`open` or by :func:`popen` or
401 :func:`fdopen`, use its :meth:`close` method.
402
403
Georg Brandl81f11302007-12-21 08:45:42 +0000404.. function:: device_encoding(fd)
405
406 Return a string describing the encoding of the device associated with *fd*
407 if it is connected to a terminal; else return :const:`None`.
408
409
Georg Brandl116aa622007-08-15 14:28:22 +0000410.. function:: dup(fd)
411
412 Return a duplicate of file descriptor *fd*. Availability: Macintosh, Unix,
413 Windows.
414
415
416.. function:: dup2(fd, fd2)
417
418 Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary.
419 Availability: Macintosh, Unix, Windows.
420
421
Christian Heimes4e30a842007-11-30 22:12:06 +0000422.. function:: fchmod(fd, mode)
423
424 Change the mode of the file given by *fd* to the numeric *mode*. See the docs
425 for :func:`chmod` for possible values of *mode*. Availability: Unix.
426
427
428.. function:: fchown(fd, uid, gid)
429
430 Change the owner and group id of the file given by *fd* to the numeric *uid*
431 and *gid*. To leave one of the ids unchanged, set it to -1.
432 Availability: Unix.
433
434
Georg Brandl116aa622007-08-15 14:28:22 +0000435.. function:: fdatasync(fd)
436
437 Force write of file with filedescriptor *fd* to disk. Does not force update of
438 metadata. Availability: Unix.
439
440
441.. function:: fpathconf(fd, name)
442
443 Return system configuration information relevant to an open file. *name*
444 specifies the configuration value to retrieve; it may be a string which is the
445 name of a defined system value; these names are specified in a number of
446 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
447 additional names as well. The names known to the host operating system are
448 given in the ``pathconf_names`` dictionary. For configuration variables not
449 included in that mapping, passing an integer for *name* is also accepted.
450 Availability: Macintosh, Unix.
451
452 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
453 specific value for *name* is not supported by the host system, even if it is
454 included in ``pathconf_names``, an :exc:`OSError` is raised with
455 :const:`errno.EINVAL` for the error number.
456
457
458.. function:: fstat(fd)
459
460 Return status for file descriptor *fd*, like :func:`stat`. Availability:
461 Macintosh, Unix, Windows.
462
463
464.. function:: fstatvfs(fd)
465
466 Return information about the filesystem containing the file associated with file
467 descriptor *fd*, like :func:`statvfs`. Availability: Unix.
468
469
470.. function:: fsync(fd)
471
472 Force write of file with filedescriptor *fd* to disk. On Unix, this calls the
473 native :cfunc:`fsync` function; on Windows, the MS :cfunc:`_commit` function.
474
475 If you're starting with a Python file object *f*, first do ``f.flush()``, and
476 then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated
477 with *f* are written to disk. Availability: Macintosh, Unix, and Windows
478 starting in 2.2.3.
479
480
481.. function:: ftruncate(fd, length)
482
483 Truncate the file corresponding to file descriptor *fd*, so that it is at most
484 *length* bytes in size. Availability: Macintosh, Unix.
485
486
487.. function:: isatty(fd)
488
489 Return ``True`` if the file descriptor *fd* is open and connected to a
490 tty(-like) device, else ``False``. Availability: Macintosh, Unix.
491
492
493.. function:: lseek(fd, pos, how)
494
495 Set the current position of file descriptor *fd* to position *pos*, modified by
496 *how*: ``0`` to set the position relative to the beginning of the file; ``1`` to
497 set it relative to the current position; ``2`` to set it relative to the end of
498 the file. Availability: Macintosh, Unix, Windows.
499
500
501.. function:: open(file, flags[, mode])
502
503 Open the file *file* and set various flags according to *flags* and possibly its
504 mode according to *mode*. The default *mode* is ``0777`` (octal), and the
505 current umask value is first masked out. Return the file descriptor for the
506 newly opened file. Availability: Macintosh, Unix, Windows.
507
508 For a description of the flag and mode values, see the C run-time documentation;
509 flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
510 this module too (see below).
511
512 .. note::
513
514 This function is intended for low-level I/O. For normal usage, use the built-in
515 function :func:`open`, which returns a "file object" with :meth:`read` and
516 :meth:`write` methods (and many more). To wrap a file descriptor in a "file
517 object", use :func:`fdopen`.
518
519
520.. function:: openpty()
521
522 .. index:: module: pty
523
524 Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master,
525 slave)`` for the pty and the tty, respectively. For a (slightly) more portable
526 approach, use the :mod:`pty` module. Availability: Macintosh, Some flavors of
527 Unix.
528
529
530.. function:: pipe()
531
532 Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading
533 and writing, respectively. Availability: Macintosh, Unix, Windows.
534
535
536.. function:: read(fd, n)
537
538 Read at most *n* bytes from file descriptor *fd*. Return a string containing the
539 bytes read. If the end of the file referred to by *fd* has been reached, an
540 empty string is returned. Availability: Macintosh, Unix, Windows.
541
542 .. note::
543
544 This function is intended for low-level I/O and must be applied to a file
545 descriptor as returned by :func:`open` or :func:`pipe`. To read a "file object"
546 returned by the built-in function :func:`open` or by :func:`popen` or
547 :func:`fdopen`, or ``sys.stdin``, use its :meth:`read` or :meth:`readline`
548 methods.
549
550
551.. function:: tcgetpgrp(fd)
552
553 Return the process group associated with the terminal given by *fd* (an open
554 file descriptor as returned by :func:`open`). Availability: Macintosh, Unix.
555
556
557.. function:: tcsetpgrp(fd, pg)
558
559 Set the process group associated with the terminal given by *fd* (an open file
560 descriptor as returned by :func:`open`) to *pg*. Availability: Macintosh, Unix.
561
562
563.. function:: ttyname(fd)
564
565 Return a string which specifies the terminal device associated with
Georg Brandl9afde1c2007-11-01 20:32:30 +0000566 file descriptor *fd*. If *fd* is not associated with a terminal device, an
Georg Brandl116aa622007-08-15 14:28:22 +0000567 exception is raised. Availability:Macintosh, Unix.
568
569
570.. function:: write(fd, str)
571
572 Write the string *str* to file descriptor *fd*. Return the number of bytes
573 actually written. Availability: Macintosh, Unix, Windows.
574
575 .. note::
576
577 This function is intended for low-level I/O and must be applied to a file
578 descriptor as returned by :func:`open` or :func:`pipe`. To write a "file
579 object" returned by the built-in function :func:`open` or by :func:`popen` or
580 :func:`fdopen`, or ``sys.stdout`` or ``sys.stderr``, use its :meth:`write`
581 method.
582
583The following data items are available for use in constructing the *flags*
584parameter to the :func:`open` function. Some items will not be available on all
585platforms. For descriptions of their availability and use, consult
586:manpage:`open(2)`.
587
588
589.. data:: O_RDONLY
590 O_WRONLY
591 O_RDWR
592 O_APPEND
593 O_CREAT
594 O_EXCL
595 O_TRUNC
596
597 Options for the *flag* argument to the :func:`open` function. These can be
598 bit-wise OR'd together. Availability: Macintosh, Unix, Windows.
599
600
601.. data:: O_DSYNC
602 O_RSYNC
603 O_SYNC
604 O_NDELAY
605 O_NONBLOCK
606 O_NOCTTY
607 O_SHLOCK
608 O_EXLOCK
609
610 More options for the *flag* argument to the :func:`open` function. Availability:
611 Macintosh, Unix.
612
613
614.. data:: O_BINARY
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000615 O_NOINHERIT
Georg Brandl116aa622007-08-15 14:28:22 +0000616 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
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000626.. data:: O_DIRECT
627 O_DIRECTORY
628 O_NOFOLLOW
629 O_NOATIME
630
631 Options for the *flag* argument to the :func:`open` function. These are
632 GNU extensions and not present if they are not defined by the C library.
633
634
Georg Brandl116aa622007-08-15 14:28:22 +0000635.. data:: SEEK_SET
636 SEEK_CUR
637 SEEK_END
638
639 Parameters to the :func:`lseek` function. Their values are 0, 1, and 2,
640 respectively. Availability: Windows, Macintosh, Unix.
641
Georg Brandl116aa622007-08-15 14:28:22 +0000642
643.. _os-file-dir:
644
645Files and Directories
646---------------------
647
648
649.. function:: access(path, mode)
650
651 Use the real uid/gid to test for access to *path*. Note that most operations
652 will use the effective uid/gid, therefore this routine can be used in a
653 suid/sgid environment to test if the invoking user has the specified access to
654 *path*. *mode* should be :const:`F_OK` to test the existence of *path*, or it
655 can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and
656 :const:`X_OK` to test permissions. Return :const:`True` if access is allowed,
657 :const:`False` if not. See the Unix man page :manpage:`access(2)` for more
658 information. Availability: Macintosh, Unix, Windows.
659
660 .. note::
661
662 Using :func:`access` to check if a user is authorized to e.g. open a file before
663 actually doing so using :func:`open` creates a security hole, because the user
664 might exploit the short time interval between checking and opening the file to
665 manipulate it.
666
667 .. note::
668
669 I/O operations may fail even when :func:`access` indicates that they would
670 succeed, particularly for operations on network filesystems which may have
671 permissions semantics beyond the usual POSIX permission-bit model.
672
673
674.. data:: F_OK
675
676 Value to pass as the *mode* parameter of :func:`access` to test the existence of
677 *path*.
678
679
680.. data:: R_OK
681
682 Value to include in the *mode* parameter of :func:`access` to test the
683 readability of *path*.
684
685
686.. data:: W_OK
687
688 Value to include in the *mode* parameter of :func:`access` to test the
689 writability of *path*.
690
691
692.. data:: X_OK
693
694 Value to include in the *mode* parameter of :func:`access` to determine if
695 *path* can be executed.
696
697
698.. function:: chdir(path)
699
700 .. index:: single: directory; changing
701
702 Change the current working directory to *path*. Availability: Macintosh, Unix,
703 Windows.
704
705
706.. function:: fchdir(fd)
707
708 Change the current working directory to the directory represented by the file
709 descriptor *fd*. The descriptor must refer to an opened directory, not an open
710 file. Availability: Unix.
711
Georg Brandl116aa622007-08-15 14:28:22 +0000712
713.. function:: getcwd()
714
715 Return a string representing the current working directory. Availability:
716 Macintosh, Unix, Windows.
717
718
719.. function:: getcwdu()
720
721 Return a Unicode object representing the current working directory.
722 Availability: Macintosh, Unix, Windows.
723
Georg Brandl116aa622007-08-15 14:28:22 +0000724
725.. function:: chflags(path, flags)
726
727 Set the flags of *path* to the numeric *flags*. *flags* may take a combination
728 (bitwise OR) of the following values (as defined in the :mod:`stat` module):
729
730 * ``UF_NODUMP``
731 * ``UF_IMMUTABLE``
732 * ``UF_APPEND``
733 * ``UF_OPAQUE``
734 * ``UF_NOUNLINK``
735 * ``SF_ARCHIVED``
736 * ``SF_IMMUTABLE``
737 * ``SF_APPEND``
738 * ``SF_NOUNLINK``
739 * ``SF_SNAPSHOT``
740
741 Availability: Macintosh, Unix.
742
Georg Brandl116aa622007-08-15 14:28:22 +0000743
744.. function:: chroot(path)
745
746 Change the root directory of the current process to *path*. Availability:
747 Macintosh, Unix.
748
Georg Brandl116aa622007-08-15 14:28:22 +0000749
750.. function:: chmod(path, mode)
751
752 Change the mode of *path* to the numeric *mode*. *mode* may take one of the
753 following values (as defined in the :mod:`stat` module) or bitwise or-ed
754 combinations of them:
755
756 * ``stat.S_ISUID``
757 * ``stat.S_ISGID``
758 * ``stat.S_ENFMT``
759 * ``stat.S_ISVTX``
760 * ``stat.S_IREAD``
761 * ``stat.S_IWRITE``
762 * ``stat.S_IEXEC``
763 * ``stat.S_IRWXU``
764 * ``stat.S_IRUSR``
765 * ``stat.S_IWUSR``
766 * ``stat.S_IXUSR``
767 * ``stat.S_IRWXG``
768 * ``stat.S_IRGRP``
769 * ``stat.S_IWGRP``
770 * ``stat.S_IXGRP``
771 * ``stat.S_IRWXO``
772 * ``stat.S_IROTH``
773 * ``stat.S_IWOTH``
774 * ``stat.S_IXOTH``
775
776 Availability: Macintosh, Unix, Windows.
777
778 .. note::
779
780 Although Windows supports :func:`chmod`, you can only set the file's read-only
781 flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD``
782 constants or a corresponding integer value). All other bits are
783 ignored.
784
785
786.. function:: chown(path, uid, gid)
787
788 Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave
789 one of the ids unchanged, set it to -1. Availability: Macintosh, Unix.
790
791
792.. function:: lchflags(path, flags)
793
794 Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not
795 follow symbolic links. Availability: Unix.
796
Georg Brandl116aa622007-08-15 14:28:22 +0000797
Christian Heimes93852662007-12-01 12:22:32 +0000798.. function:: lchmod(path, mode)
799
800 Change the mode of *path* to the numeric *mode*. If path is a symlink, this
801 affects the symlink rather than the target. See the docs for :func:`chmod`
802 for possible values of *mode*. Availability: Unix.
803
Christian Heimes93852662007-12-01 12:22:32 +0000804
Georg Brandl116aa622007-08-15 14:28:22 +0000805.. function:: lchown(path, uid, gid)
806
807 Change the owner and group id of *path* to the numeric *uid* and gid. This
808 function will not follow symbolic links. Availability: Macintosh, Unix.
809
Georg Brandl116aa622007-08-15 14:28:22 +0000810
811.. function:: link(src, dst)
812
813 Create a hard link pointing to *src* named *dst*. Availability: Macintosh, Unix.
814
815
816.. function:: listdir(path)
817
818 Return a list containing the names of the entries in the directory. The list is
819 in arbitrary order. It does not include the special entries ``'.'`` and
820 ``'..'`` even if they are present in the directory. Availability: Macintosh,
821 Unix, Windows.
822
Georg Brandl55ac8f02007-09-01 13:51:09 +0000823 On Windows NT/2k/XP and Unix, if *path* is a Unicode object, the result will be
824 a list of Unicode objects.
Georg Brandl116aa622007-08-15 14:28:22 +0000825
826
827.. function:: lstat(path)
828
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000829 Like :func:`stat`, but do not follow symbolic links. This is an alias for
830 :func:`stat` on platforms that do not support symbolic links, such as
831 Windows.
Georg Brandl116aa622007-08-15 14:28:22 +0000832
833
834.. function:: mkfifo(path[, mode])
835
836 Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The default
837 *mode* is ``0666`` (octal). The current umask value is first masked out from
838 the mode. Availability: Macintosh, Unix.
839
840 FIFOs are pipes that can be accessed like regular files. FIFOs exist until they
841 are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
842 rendezvous between "client" and "server" type processes: the server opens the
843 FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo`
844 doesn't open the FIFO --- it just creates the rendezvous point.
845
846
847.. function:: mknod(filename[, mode=0600, device])
848
849 Create a filesystem node (file, device special file or named pipe) named
850 *filename*. *mode* specifies both the permissions to use and the type of node to
851 be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
852 ``stat.S_IFCHR``, ``stat.S_IFBLK``,
853 and ``stat.S_IFIFO`` (those constants are available in :mod:`stat`).
854 For ``stat.S_IFCHR`` and
855 ``stat.S_IFBLK``, *device* defines the newly created device special file (probably using
856 :func:`os.makedev`), otherwise it is ignored.
857
Georg Brandl116aa622007-08-15 14:28:22 +0000858
859.. function:: major(device)
860
861 Extracts the device major number from a raw device number (usually the
862 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
863
Georg Brandl116aa622007-08-15 14:28:22 +0000864
865.. function:: minor(device)
866
867 Extracts the device minor number from a raw device number (usually the
868 :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
869
Georg Brandl116aa622007-08-15 14:28:22 +0000870
871.. function:: makedev(major, minor)
872
873 Composes a raw device number from the major and minor device numbers.
874
Georg Brandl116aa622007-08-15 14:28:22 +0000875
876.. function:: mkdir(path[, mode])
877
878 Create a directory named *path* with numeric mode *mode*. The default *mode* is
879 ``0777`` (octal). On some systems, *mode* is ignored. Where it is used, the
880 current umask value is first masked out. Availability: Macintosh, Unix, Windows.
881
Guido van Rossum2cc30da2007-11-02 23:46:40 +0000882 It is also possible to create temporary directories; see the
883 :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
884
Georg Brandl116aa622007-08-15 14:28:22 +0000885
886.. function:: makedirs(path[, mode])
887
888 .. index::
889 single: directory; creating
890 single: UNC paths; and os.makedirs()
891
892 Recursive directory creation function. Like :func:`mkdir`, but makes all
893 intermediate-level directories needed to contain the leaf directory. Throws an
894 :exc:`error` exception if the leaf directory already exists or cannot be
895 created. The default *mode* is ``0777`` (octal). On some systems, *mode* is
896 ignored. Where it is used, the current umask value is first masked out.
897
898 .. note::
899
900 :func:`makedirs` will become confused if the path elements to create include
901 *os.pardir*.
902
Georg Brandl55ac8f02007-09-01 13:51:09 +0000903 This function handles UNC paths correctly.
Georg Brandl116aa622007-08-15 14:28:22 +0000904
905
906.. function:: pathconf(path, name)
907
908 Return system configuration information relevant to a named file. *name*
909 specifies the configuration value to retrieve; it may be a string which is the
910 name of a defined system value; these names are specified in a number of
911 standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
912 additional names as well. The names known to the host operating system are
913 given in the ``pathconf_names`` dictionary. For configuration variables not
914 included in that mapping, passing an integer for *name* is also accepted.
915 Availability: Macintosh, Unix.
916
917 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
918 specific value for *name* is not supported by the host system, even if it is
919 included in ``pathconf_names``, an :exc:`OSError` is raised with
920 :const:`errno.EINVAL` for the error number.
921
922
923.. data:: pathconf_names
924
925 Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
926 the integer values defined for those names by the host operating system. This
927 can be used to determine the set of names known to the system. Availability:
928 Macintosh, Unix.
929
930
931.. function:: readlink(path)
932
933 Return a string representing the path to which the symbolic link points. The
934 result may be either an absolute or relative pathname; if it is relative, it may
935 be converted to an absolute pathname using ``os.path.join(os.path.dirname(path),
936 result)``.
937
Georg Brandl55ac8f02007-09-01 13:51:09 +0000938 If the *path* is a Unicode object, the result will also be a Unicode object.
Georg Brandl116aa622007-08-15 14:28:22 +0000939
940 Availability: Macintosh, Unix.
941
942
943.. function:: remove(path)
944
945 Remove the file *path*. If *path* is a directory, :exc:`OSError` is raised; see
946 :func:`rmdir` below to remove a directory. This is identical to the
947 :func:`unlink` function documented below. On Windows, attempting to remove a
948 file that is in use causes an exception to be raised; on Unix, the directory
949 entry is removed but the storage allocated to the file is not made available
950 until the original file is no longer in use. Availability: Macintosh, Unix,
951 Windows.
952
953
954.. function:: removedirs(path)
955
956 .. index:: single: directory; deleting
957
958 Removes directories recursively. Works like :func:`rmdir` except that, if the
959 leaf directory is successfully removed, :func:`removedirs` tries to
960 successively remove every parent directory mentioned in *path* until an error
961 is raised (which is ignored, because it generally means that a parent directory
962 is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
963 the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
964 they are empty. Raises :exc:`OSError` if the leaf directory could not be
965 successfully removed.
966
Georg Brandl116aa622007-08-15 14:28:22 +0000967
968.. function:: rename(src, dst)
969
970 Rename the file or directory *src* to *dst*. If *dst* is a directory,
971 :exc:`OSError` will be raised. On Unix, if *dst* exists and is a file, it will
972 be removed silently if the user has permission. The operation may fail on some
973 Unix flavors if *src* and *dst* are on different filesystems. If successful,
974 the renaming will be an atomic operation (this is a POSIX requirement). On
975 Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a
976 file; there may be no way to implement an atomic rename when *dst* names an
977 existing file. Availability: Macintosh, Unix, Windows.
978
979
980.. function:: renames(old, new)
981
982 Recursive directory or file renaming function. Works like :func:`rename`, except
983 creation of any intermediate directories needed to make the new pathname good is
984 attempted first. After the rename, directories corresponding to rightmost path
985 segments of the old name will be pruned away using :func:`removedirs`.
986
Georg Brandl116aa622007-08-15 14:28:22 +0000987 .. note::
988
989 This function can fail with the new directory structure made if you lack
990 permissions needed to remove the leaf directory or file.
991
992
993.. function:: rmdir(path)
994
995 Remove the directory *path*. Availability: Macintosh, Unix, Windows.
996
997
998.. function:: stat(path)
999
1000 Perform a :cfunc:`stat` system call on the given path. The return value is an
1001 object whose attributes correspond to the members of the :ctype:`stat`
1002 structure, namely: :attr:`st_mode` (protection bits), :attr:`st_ino` (inode
1003 number), :attr:`st_dev` (device), :attr:`st_nlink` (number of hard links),
1004 :attr:`st_uid` (user ID of owner), :attr:`st_gid` (group ID of owner),
1005 :attr:`st_size` (size of file, in bytes), :attr:`st_atime` (time of most recent
1006 access), :attr:`st_mtime` (time of most recent content modification),
1007 :attr:`st_ctime` (platform dependent; time of most recent metadata change on
1008 Unix, or the time of creation on Windows)::
1009
1010 >>> import os
1011 >>> statinfo = os.stat('somefile.txt')
1012 >>> statinfo
1013 (33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
1014 >>> statinfo.st_size
1015 926L
1016 >>>
1017
Georg Brandl55ac8f02007-09-01 13:51:09 +00001018 If :func:`stat_float_times` returns true, the time values are floats, measuring
1019 seconds. Fractions of a second may be reported if the system supports that. On
1020 Mac OS, the times are always floats. See :func:`stat_float_times` for further
1021 discussion.
Georg Brandl116aa622007-08-15 14:28:22 +00001022
1023 On some Unix systems (such as Linux), the following attributes may also be
1024 available: :attr:`st_blocks` (number of blocks allocated for file),
1025 :attr:`st_blksize` (filesystem blocksize), :attr:`st_rdev` (type of device if an
1026 inode device). :attr:`st_flags` (user defined flags for file).
1027
1028 On other Unix systems (such as FreeBSD), the following attributes may be
1029 available (but may be only filled out if root tries to use them): :attr:`st_gen`
1030 (file generation number), :attr:`st_birthtime` (time of file creation).
1031
1032 On Mac OS systems, the following attributes may also be available:
1033 :attr:`st_rsize`, :attr:`st_creator`, :attr:`st_type`.
1034
Georg Brandl116aa622007-08-15 14:28:22 +00001035 .. index:: module: stat
1036
1037 For backward compatibility, the return value of :func:`stat` is also accessible
1038 as a tuple of at least 10 integers giving the most important (and portable)
1039 members of the :ctype:`stat` structure, in the order :attr:`st_mode`,
1040 :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, :attr:`st_uid`,
1041 :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, :attr:`st_mtime`,
1042 :attr:`st_ctime`. More items may be added at the end by some implementations.
1043 The standard module :mod:`stat` defines functions and constants that are useful
1044 for extracting information from a :ctype:`stat` structure. (On Windows, some
1045 items are filled with dummy values.)
1046
1047 .. note::
1048
1049 The exact meaning and resolution of the :attr:`st_atime`, :attr:`st_mtime`, and
1050 :attr:`st_ctime` members depends on the operating system and the file system.
1051 For example, on Windows systems using the FAT or FAT32 file systems,
1052 :attr:`st_mtime` has 2-second resolution, and :attr:`st_atime` has only 1-day
1053 resolution. See your operating system documentation for details.
1054
1055 Availability: Macintosh, Unix, Windows.
1056
Georg Brandl116aa622007-08-15 14:28:22 +00001057
1058.. function:: stat_float_times([newvalue])
1059
1060 Determine whether :class:`stat_result` represents time stamps as float objects.
1061 If *newvalue* is ``True``, future calls to :func:`stat` return floats, if it is
1062 ``False``, future calls return ints. If *newvalue* is omitted, return the
1063 current setting.
1064
1065 For compatibility with older Python versions, accessing :class:`stat_result` as
1066 a tuple always returns integers.
1067
Georg Brandl55ac8f02007-09-01 13:51:09 +00001068 Python now returns float values by default. Applications which do not work
1069 correctly with floating point time stamps can use this function to restore the
1070 old behaviour.
Georg Brandl116aa622007-08-15 14:28:22 +00001071
1072 The resolution of the timestamps (that is the smallest possible fraction)
1073 depends on the system. Some systems only support second resolution; on these
1074 systems, the fraction will always be zero.
1075
1076 It is recommended that this setting is only changed at program startup time in
1077 the *__main__* module; libraries should never change this setting. If an
1078 application uses a library that works incorrectly if floating point time stamps
1079 are processed, this application should turn the feature off until the library
1080 has been corrected.
1081
1082
1083.. function:: statvfs(path)
1084
1085 Perform a :cfunc:`statvfs` system call on the given path. The return value is
1086 an object whose attributes describe the filesystem on the given path, and
1087 correspond to the members of the :ctype:`statvfs` structure, namely:
1088 :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
1089 :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
1090 :attr:`f_flag`, :attr:`f_namemax`. Availability: Unix.
1091
1092 .. index:: module: statvfs
1093
1094 For backward compatibility, the return value is also accessible as a tuple whose
1095 values correspond to the attributes, in the order given above. The standard
1096 module :mod:`statvfs` defines constants that are useful for extracting
1097 information from a :ctype:`statvfs` structure when accessing it as a sequence;
1098 this remains useful when writing code that needs to work with versions of Python
1099 that don't support accessing the fields as attributes.
1100
Georg Brandl116aa622007-08-15 14:28:22 +00001101
1102.. function:: symlink(src, dst)
1103
1104 Create a symbolic link pointing to *src* named *dst*. Availability: Unix.
1105
1106
Georg Brandl116aa622007-08-15 14:28:22 +00001107.. function:: unlink(path)
1108
1109 Remove the file *path*. This is the same function as :func:`remove`; the
1110 :func:`unlink` name is its traditional Unix name. Availability: Macintosh, Unix,
1111 Windows.
1112
1113
1114.. function:: utime(path, times)
1115
1116 Set the access and modified times of the file specified by *path*. If *times* is
1117 ``None``, then the file's access and modified times are set to the current time.
1118 Otherwise, *times* must be a 2-tuple of numbers, of the form ``(atime, mtime)``
1119 which is used to set the access and modified times, respectively. Whether a
1120 directory can be given for *path* depends on whether the operating system
1121 implements directories as files (for example, Windows does not). Note that the
1122 exact times you set here may not be returned by a subsequent :func:`stat` call,
1123 depending on the resolution with which your operating system records access and
1124 modification times; see :func:`stat`.
1125
Georg Brandl116aa622007-08-15 14:28:22 +00001126 Availability: Macintosh, Unix, Windows.
1127
1128
1129.. function:: walk(top[, topdown=True [, onerror=None[, followlinks=False]]])
1130
1131 .. index::
1132 single: directory; walking
1133 single: directory; traversal
1134
1135 :func:`walk` generates the file names in a directory tree, by walking the tree
1136 either top down or bottom up. For each directory in the tree rooted at directory
1137 *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
1138 filenames)``.
1139
1140 *dirpath* is a string, the path to the directory. *dirnames* is a list of the
1141 names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``).
1142 *filenames* is a list of the names of the non-directory files in *dirpath*.
1143 Note that the names in the lists contain no path components. To get a full path
1144 (which begins with *top*) to a file or directory in *dirpath*, do
1145 ``os.path.join(dirpath, name)``.
1146
1147 If optional argument *topdown* is true or not specified, the triple for a
1148 directory is generated before the triples for any of its subdirectories
1149 (directories are generated top down). If *topdown* is false, the triple for a
1150 directory is generated after the triples for all of its subdirectories
1151 (directories are generated bottom up).
1152
1153 When *topdown* is true, the caller can modify the *dirnames* list in-place
1154 (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
1155 recurse into the subdirectories whose names remain in *dirnames*; this can be
1156 used to prune the search, impose a specific order of visiting, or even to inform
1157 :func:`walk` about directories the caller creates or renames before it resumes
1158 :func:`walk` again. Modifying *dirnames* when *topdown* is false is
1159 ineffective, because in bottom-up mode the directories in *dirnames* are
1160 generated before *dirpath* itself is generated.
1161
1162 By default errors from the ``os.listdir()`` call are ignored. If optional
1163 argument *onerror* is specified, it should be a function; it will be called with
1164 one argument, an :exc:`OSError` instance. It can report the error to continue
1165 with the walk, or raise the exception to abort the walk. Note that the filename
1166 is available as the ``filename`` attribute of the exception object.
1167
1168 By default, :func:`walk` will not walk down into symbolic links that resolve to
1169 directories. Set *followlinks* to True to visit directories pointed to by
1170 symlinks, on systems that support them.
1171
Georg Brandl116aa622007-08-15 14:28:22 +00001172 .. note::
1173
1174 Be aware that setting *followlinks* to true can lead to infinite recursion if a
1175 link points to a parent directory of itself. :func:`walk` does not keep track of
1176 the directories it visited already.
1177
1178 .. note::
1179
1180 If you pass a relative pathname, don't change the current working directory
1181 between resumptions of :func:`walk`. :func:`walk` never changes the current
1182 directory, and assumes that its caller doesn't either.
1183
1184 This example displays the number of bytes taken by non-directory files in each
1185 directory under the starting directory, except that it doesn't look under any
1186 CVS subdirectory::
1187
1188 import os
1189 from os.path import join, getsize
1190 for root, dirs, files in os.walk('python/Lib/email'):
Georg Brandl6911e3c2007-09-04 07:15:32 +00001191 print(root, "consumes", end=" ")
1192 print(sum(getsize(join(root, name)) for name in files), end=" ")
1193 print("bytes in", len(files), "non-directory files")
Georg Brandl116aa622007-08-15 14:28:22 +00001194 if 'CVS' in dirs:
1195 dirs.remove('CVS') # don't visit CVS directories
1196
1197 In the next example, walking the tree bottom up is essential: :func:`rmdir`
1198 doesn't allow deleting a directory before the directory is empty::
1199
1200 # Delete everything reachable from the directory named in 'top',
1201 # assuming there are no symbolic links.
1202 # CAUTION: This is dangerous! For example, if top == '/', it
1203 # could delete all your disk files.
1204 import os
1205 for root, dirs, files in os.walk(top, topdown=False):
1206 for name in files:
1207 os.remove(os.path.join(root, name))
1208 for name in dirs:
1209 os.rmdir(os.path.join(root, name))
1210
Georg Brandl116aa622007-08-15 14:28:22 +00001211
1212.. _os-process:
1213
1214Process Management
1215------------------
1216
1217These functions may be used to create and manage processes.
1218
1219The various :func:`exec\*` functions take a list of arguments for the new
1220program loaded into the process. In each case, the first of these arguments is
1221passed to the new program as its own name rather than as an argument a user may
1222have typed on a command line. For the C programmer, this is the ``argv[0]``
1223passed to a program's :cfunc:`main`. For example, ``os.execv('/bin/echo',
1224['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
1225to be ignored.
1226
1227
1228.. function:: abort()
1229
1230 Generate a :const:`SIGABRT` signal to the current process. On Unix, the default
1231 behavior is to produce a core dump; on Windows, the process immediately returns
1232 an exit code of ``3``. Be aware that programs which use :func:`signal.signal`
1233 to register a handler for :const:`SIGABRT` will behave differently.
1234 Availability: Macintosh, Unix, Windows.
1235
1236
1237.. function:: execl(path, arg0, arg1, ...)
1238 execle(path, arg0, arg1, ..., env)
1239 execlp(file, arg0, arg1, ...)
1240 execlpe(file, arg0, arg1, ..., env)
1241 execv(path, args)
1242 execve(path, args, env)
1243 execvp(file, args)
1244 execvpe(file, args, env)
1245
1246 These functions all execute a new program, replacing the current process; they
1247 do not return. On Unix, the new executable is loaded into the current process,
1248 and will have the same process ID as the caller. Errors will be reported as
1249 :exc:`OSError` exceptions.
1250
1251 The ``'l'`` and ``'v'`` variants of the :func:`exec\*` functions differ in how
1252 command-line arguments are passed. The ``'l'`` variants are perhaps the easiest
1253 to work with if the number of parameters is fixed when the code is written; the
1254 individual parameters simply become additional parameters to the :func:`execl\*`
1255 functions. The ``'v'`` variants are good when the number of parameters is
1256 variable, with the arguments being passed in a list or tuple as the *args*
1257 parameter. In either case, the arguments to the child process should start with
1258 the name of the command being run, but this is not enforced.
1259
1260 The variants which include a ``'p'`` near the end (:func:`execlp`,
1261 :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
1262 :envvar:`PATH` environment variable to locate the program *file*. When the
1263 environment is being replaced (using one of the :func:`exec\*e` variants,
1264 discussed in the next paragraph), the new environment is used as the source of
1265 the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
1266 :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
1267 locate the executable; *path* must contain an appropriate absolute or relative
1268 path.
1269
1270 For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
1271 that these all end in ``'e'``), the *env* parameter must be a mapping which is
1272 used to define the environment variables for the new process; the :func:`execl`,
1273 :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
1274 inherit the environment of the current process. Availability: Macintosh, Unix,
1275 Windows.
1276
1277
1278.. function:: _exit(n)
1279
1280 Exit to the system with status *n*, without calling cleanup handlers, flushing
1281 stdio buffers, etc. Availability: Macintosh, Unix, Windows.
1282
1283 .. note::
1284
1285 The standard way to exit is ``sys.exit(n)``. :func:`_exit` should normally only
1286 be used in the child process after a :func:`fork`.
1287
1288The following exit codes are a defined, and can be used with :func:`_exit`,
1289although they are not required. These are typically used for system programs
1290written in Python, such as a mail server's external command delivery program.
1291
1292.. note::
1293
1294 Some of these may not be available on all Unix platforms, since there is some
1295 variation. These constants are defined where they are defined by the underlying
1296 platform.
1297
1298
1299.. data:: EX_OK
1300
1301 Exit code that means no error occurred. Availability: Macintosh, Unix.
1302
Georg Brandl116aa622007-08-15 14:28:22 +00001303
1304.. data:: EX_USAGE
1305
1306 Exit code that means the command was used incorrectly, such as when the wrong
1307 number of arguments are given. Availability: Macintosh, Unix.
1308
Georg Brandl116aa622007-08-15 14:28:22 +00001309
1310.. data:: EX_DATAERR
1311
1312 Exit code that means the input data was incorrect. Availability: Macintosh,
1313 Unix.
1314
Georg Brandl116aa622007-08-15 14:28:22 +00001315
1316.. data:: EX_NOINPUT
1317
1318 Exit code that means an input file did not exist or was not readable.
1319 Availability: Macintosh, Unix.
1320
Georg Brandl116aa622007-08-15 14:28:22 +00001321
1322.. data:: EX_NOUSER
1323
1324 Exit code that means a specified user did not exist. Availability: Macintosh,
1325 Unix.
1326
Georg Brandl116aa622007-08-15 14:28:22 +00001327
1328.. data:: EX_NOHOST
1329
1330 Exit code that means a specified host did not exist. Availability: Macintosh,
1331 Unix.
1332
Georg Brandl116aa622007-08-15 14:28:22 +00001333
1334.. data:: EX_UNAVAILABLE
1335
1336 Exit code that means that a required service is unavailable. Availability:
1337 Macintosh, Unix.
1338
Georg Brandl116aa622007-08-15 14:28:22 +00001339
1340.. data:: EX_SOFTWARE
1341
1342 Exit code that means an internal software error was detected. Availability:
1343 Macintosh, Unix.
1344
Georg Brandl116aa622007-08-15 14:28:22 +00001345
1346.. data:: EX_OSERR
1347
1348 Exit code that means an operating system error was detected, such as the
1349 inability to fork or create a pipe. Availability: Macintosh, Unix.
1350
Georg Brandl116aa622007-08-15 14:28:22 +00001351
1352.. data:: EX_OSFILE
1353
1354 Exit code that means some system file did not exist, could not be opened, or had
1355 some other kind of error. Availability: Macintosh, Unix.
1356
Georg Brandl116aa622007-08-15 14:28:22 +00001357
1358.. data:: EX_CANTCREAT
1359
1360 Exit code that means a user specified output file could not be created.
1361 Availability: Macintosh, Unix.
1362
Georg Brandl116aa622007-08-15 14:28:22 +00001363
1364.. data:: EX_IOERR
1365
1366 Exit code that means that an error occurred while doing I/O on some file.
1367 Availability: Macintosh, Unix.
1368
Georg Brandl116aa622007-08-15 14:28:22 +00001369
1370.. data:: EX_TEMPFAIL
1371
1372 Exit code that means a temporary failure occurred. This indicates something
1373 that may not really be an error, such as a network connection that couldn't be
1374 made during a retryable operation. Availability: Macintosh, Unix.
1375
Georg Brandl116aa622007-08-15 14:28:22 +00001376
1377.. data:: EX_PROTOCOL
1378
1379 Exit code that means that a protocol exchange was illegal, invalid, or not
1380 understood. Availability: Macintosh, Unix.
1381
Georg Brandl116aa622007-08-15 14:28:22 +00001382
1383.. data:: EX_NOPERM
1384
1385 Exit code that means that there were insufficient permissions to perform the
1386 operation (but not intended for file system problems). Availability: Macintosh,
1387 Unix.
1388
Georg Brandl116aa622007-08-15 14:28:22 +00001389
1390.. data:: EX_CONFIG
1391
1392 Exit code that means that some kind of configuration error occurred.
1393 Availability: Macintosh, Unix.
1394
Georg Brandl116aa622007-08-15 14:28:22 +00001395
1396.. data:: EX_NOTFOUND
1397
1398 Exit code that means something like "an entry was not found". Availability:
1399 Macintosh, Unix.
1400
Georg Brandl116aa622007-08-15 14:28:22 +00001401
1402.. function:: fork()
1403
1404 Fork a child process. Return ``0`` in the child, the child's process id in the
1405 parent. Availability: Macintosh, Unix.
1406
1407
1408.. function:: forkpty()
1409
1410 Fork a child process, using a new pseudo-terminal as the child's controlling
1411 terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
1412 new child's process id in the parent, and *fd* is the file descriptor of the
1413 master end of the pseudo-terminal. For a more portable approach, use the
1414 :mod:`pty` module. Availability: Macintosh, Some flavors of Unix.
1415
1416
1417.. function:: kill(pid, sig)
1418
1419 .. index::
1420 single: process; killing
1421 single: process; signalling
1422
1423 Send signal *sig* to the process *pid*. Constants for the specific signals
1424 available on the host platform are defined in the :mod:`signal` module.
1425 Availability: Macintosh, Unix.
1426
1427
1428.. function:: killpg(pgid, sig)
1429
1430 .. index::
1431 single: process; killing
1432 single: process; signalling
1433
1434 Send the signal *sig* to the process group *pgid*. Availability: Macintosh,
1435 Unix.
1436
Georg Brandl116aa622007-08-15 14:28:22 +00001437
1438.. function:: nice(increment)
1439
1440 Add *increment* to the process's "niceness". Return the new niceness.
1441 Availability: Macintosh, Unix.
1442
1443
1444.. function:: plock(op)
1445
1446 Lock program segments into memory. The value of *op* (defined in
1447 ``<sys/lock.h>``) determines which segments are locked. Availability: Macintosh,
1448 Unix.
1449
1450
1451.. function:: popen(...)
1452 :noindex:
1453
1454 Run child processes, returning opened pipes for communications. These functions
1455 are described in section :ref:`os-newstreams`.
1456
1457
1458.. function:: spawnl(mode, path, ...)
1459 spawnle(mode, path, ..., env)
1460 spawnlp(mode, file, ...)
1461 spawnlpe(mode, file, ..., env)
1462 spawnv(mode, path, args)
1463 spawnve(mode, path, args, env)
1464 spawnvp(mode, file, args)
1465 spawnvpe(mode, file, args, env)
1466
1467 Execute the program *path* in a new process.
1468
1469 (Note that the :mod:`subprocess` module provides more powerful facilities for
1470 spawning new processes and retrieving their results; using that module is
1471 preferable to using these functions.)
1472
1473 If *mode* is :const:`P_NOWAIT`, this function returns the process ID of the new
1474 process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
1475 exits normally, or ``-signal``, where *signal* is the signal that killed the
1476 process. On Windows, the process ID will actually be the process handle, so can
1477 be used with the :func:`waitpid` function.
1478
1479 The ``'l'`` and ``'v'`` variants of the :func:`spawn\*` functions differ in how
1480 command-line arguments are passed. The ``'l'`` variants are perhaps the easiest
1481 to work with if the number of parameters is fixed when the code is written; the
1482 individual parameters simply become additional parameters to the
1483 :func:`spawnl\*` functions. The ``'v'`` variants are good when the number of
1484 parameters is variable, with the arguments being passed in a list or tuple as
1485 the *args* parameter. In either case, the arguments to the child process must
1486 start with the name of the command being run.
1487
1488 The variants which include a second ``'p'`` near the end (:func:`spawnlp`,
1489 :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
1490 :envvar:`PATH` environment variable to locate the program *file*. When the
1491 environment is being replaced (using one of the :func:`spawn\*e` variants,
1492 discussed in the next paragraph), the new environment is used as the source of
1493 the :envvar:`PATH` variable. The other variants, :func:`spawnl`,
1494 :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
1495 :envvar:`PATH` variable to locate the executable; *path* must contain an
1496 appropriate absolute or relative path.
1497
1498 For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
1499 (note that these all end in ``'e'``), the *env* parameter must be a mapping
1500 which is used to define the environment variables for the new process; the
1501 :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
1502 the new process to inherit the environment of the current process.
1503
1504 As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are
1505 equivalent::
1506
1507 import os
1508 os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
1509
1510 L = ['cp', 'index.html', '/dev/null']
1511 os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
1512
1513 Availability: Unix, Windows. :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
1514 and :func:`spawnvpe` are not available on Windows.
1515
Georg Brandl116aa622007-08-15 14:28:22 +00001516
1517.. data:: P_NOWAIT
1518 P_NOWAITO
1519
1520 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1521 functions. If either of these values is given, the :func:`spawn\*` functions
1522 will return as soon as the new process has been created, with the process ID as
1523 the return value. Availability: Macintosh, Unix, Windows.
1524
Georg Brandl116aa622007-08-15 14:28:22 +00001525
1526.. data:: P_WAIT
1527
1528 Possible value for the *mode* parameter to the :func:`spawn\*` family of
1529 functions. If this is given as *mode*, the :func:`spawn\*` functions will not
1530 return until the new process has run to completion and will return the exit code
1531 of the process the run is successful, or ``-signal`` if a signal kills the
1532 process. Availability: Macintosh, Unix, Windows.
1533
Georg Brandl116aa622007-08-15 14:28:22 +00001534
1535.. data:: P_DETACH
1536 P_OVERLAY
1537
1538 Possible values for the *mode* parameter to the :func:`spawn\*` family of
1539 functions. These are less portable than those listed above. :const:`P_DETACH`
1540 is similar to :const:`P_NOWAIT`, but the new process is detached from the
1541 console of the calling process. If :const:`P_OVERLAY` is used, the current
1542 process will be replaced; the :func:`spawn\*` function will not return.
1543 Availability: Windows.
1544
Georg Brandl116aa622007-08-15 14:28:22 +00001545
1546.. function:: startfile(path[, operation])
1547
1548 Start a file with its associated application.
1549
1550 When *operation* is not specified or ``'open'``, this acts like double-clicking
1551 the file in Windows Explorer, or giving the file name as an argument to the
1552 :program:`start` command from the interactive command shell: the file is opened
1553 with whatever application (if any) its extension is associated.
1554
1555 When another *operation* is given, it must be a "command verb" that specifies
1556 what should be done with the file. Common verbs documented by Microsoft are
1557 ``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` and
1558 ``'find'`` (to be used on directories).
1559
1560 :func:`startfile` returns as soon as the associated application is launched.
1561 There is no option to wait for the application to close, and no way to retrieve
1562 the application's exit status. The *path* parameter is relative to the current
1563 directory. If you want to use an absolute path, make sure the first character
1564 is not a slash (``'/'``); the underlying Win32 :cfunc:`ShellExecute` function
1565 doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that
1566 the path is properly encoded for Win32. Availability: Windows.
1567
Georg Brandl116aa622007-08-15 14:28:22 +00001568
1569.. function:: system(command)
1570
1571 Execute the command (a string) in a subshell. This is implemented by calling
1572 the Standard C function :cfunc:`system`, and has the same limitations. Changes
1573 to ``posix.environ``, ``sys.stdin``, etc. are not reflected in the environment
1574 of the executed command.
1575
1576 On Unix, the return value is the exit status of the process encoded in the
1577 format specified for :func:`wait`. Note that POSIX does not specify the meaning
1578 of the return value of the C :cfunc:`system` function, so the return value of
1579 the Python function is system-dependent.
1580
1581 On Windows, the return value is that returned by the system shell after running
1582 *command*, given by the Windows environment variable :envvar:`COMSPEC`: on
1583 :program:`command.com` systems (Windows 95, 98 and ME) this is always ``0``; on
1584 :program:`cmd.exe` systems (Windows NT, 2000 and XP) this is the exit status of
1585 the command run; on systems using a non-native shell, consult your shell
1586 documentation.
1587
1588 Availability: Macintosh, Unix, Windows.
1589
1590 The :mod:`subprocess` module provides more powerful facilities for spawning new
1591 processes and retrieving their results; using that module is preferable to using
1592 this function.
1593
1594
1595.. function:: times()
1596
1597 Return a 5-tuple of floating point numbers indicating accumulated (processor or
1598 other) times, in seconds. The items are: user time, system time, children's
1599 user time, children's system time, and elapsed real time since a fixed point in
1600 the past, in that order. See the Unix manual page :manpage:`times(2)` or the
1601 corresponding Windows Platform API documentation. Availability: Macintosh, Unix,
1602 Windows.
1603
1604
1605.. function:: wait()
1606
1607 Wait for completion of a child process, and return a tuple containing its pid
1608 and exit status indication: a 16-bit number, whose low byte is the signal number
1609 that killed the process, and whose high byte is the exit status (if the signal
1610 number is zero); the high bit of the low byte is set if a core file was
1611 produced. Availability: Macintosh, Unix.
1612
1613
1614.. function:: waitpid(pid, options)
1615
1616 The details of this function differ on Unix and Windows.
1617
1618 On Unix: Wait for completion of a child process given by process id *pid*, and
1619 return a tuple containing its process id and exit status indication (encoded as
1620 for :func:`wait`). The semantics of the call are affected by the value of the
1621 integer *options*, which should be ``0`` for normal operation.
1622
1623 If *pid* is greater than ``0``, :func:`waitpid` requests status information for
1624 that specific process. If *pid* is ``0``, the request is for the status of any
1625 child in the process group of the current process. If *pid* is ``-1``, the
1626 request pertains to any child of the current process. If *pid* is less than
1627 ``-1``, status is requested for any process in the process group ``-pid`` (the
1628 absolute value of *pid*).
1629
1630 On Windows: Wait for completion of a process given by process handle *pid*, and
1631 return a tuple containing *pid*, and its exit status shifted left by 8 bits
1632 (shifting makes cross-platform use of the function easier). A *pid* less than or
1633 equal to ``0`` has no special meaning on Windows, and raises an exception. The
1634 value of integer *options* has no effect. *pid* can refer to any process whose
1635 id is known, not necessarily a child process. The :func:`spawn` functions called
1636 with :const:`P_NOWAIT` return suitable process handles.
1637
1638
1639.. function:: wait3([options])
1640
1641 Similar to :func:`waitpid`, except no process id argument is given and a
1642 3-element tuple containing the child's process id, exit status indication, and
1643 resource usage information is returned. Refer to :mod:`resource`.\
1644 :func:`getrusage` for details on resource usage information. The option
1645 argument is the same as that provided to :func:`waitpid` and :func:`wait4`.
1646 Availability: Unix.
1647
Georg Brandl116aa622007-08-15 14:28:22 +00001648
1649.. function:: wait4(pid, options)
1650
1651 Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
1652 process id, exit status indication, and resource usage information is returned.
1653 Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage
1654 information. The arguments to :func:`wait4` are the same as those provided to
1655 :func:`waitpid`. Availability: Unix.
1656
Georg Brandl116aa622007-08-15 14:28:22 +00001657
1658.. data:: WNOHANG
1659
1660 The option for :func:`waitpid` to return immediately if no child process status
1661 is available immediately. The function returns ``(0, 0)`` in this case.
1662 Availability: Macintosh, Unix.
1663
1664
1665.. data:: WCONTINUED
1666
1667 This option causes child processes to be reported if they have been continued
1668 from a job control stop since their status was last reported. Availability: Some
1669 Unix systems.
1670
Georg Brandl116aa622007-08-15 14:28:22 +00001671
1672.. data:: WUNTRACED
1673
1674 This option causes child processes to be reported if they have been stopped but
1675 their current state has not been reported since they were stopped. Availability:
1676 Macintosh, Unix.
1677
Georg Brandl116aa622007-08-15 14:28:22 +00001678
1679The following functions take a process status code as returned by
1680:func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be
1681used to determine the disposition of a process.
1682
Georg Brandl116aa622007-08-15 14:28:22 +00001683.. function:: WCOREDUMP(status)
1684
1685 Returns ``True`` if a core dump was generated for the process, otherwise it
1686 returns ``False``. Availability: Macintosh, Unix.
1687
Georg Brandl116aa622007-08-15 14:28:22 +00001688
1689.. function:: WIFCONTINUED(status)
1690
1691 Returns ``True`` if the process has been continued from a job control stop,
1692 otherwise it returns ``False``. Availability: Unix.
1693
Georg Brandl116aa622007-08-15 14:28:22 +00001694
1695.. function:: WIFSTOPPED(status)
1696
1697 Returns ``True`` if the process has been stopped, otherwise it returns
1698 ``False``. Availability: Unix.
1699
1700
1701.. function:: WIFSIGNALED(status)
1702
1703 Returns ``True`` if the process exited due to a signal, otherwise it returns
1704 ``False``. Availability: Macintosh, Unix.
1705
1706
1707.. function:: WIFEXITED(status)
1708
1709 Returns ``True`` if the process exited using the :manpage:`exit(2)` system call,
1710 otherwise it returns ``False``. Availability: Macintosh, Unix.
1711
1712
1713.. function:: WEXITSTATUS(status)
1714
1715 If ``WIFEXITED(status)`` is true, return the integer parameter to the
1716 :manpage:`exit(2)` system call. Otherwise, the return value is meaningless.
1717 Availability: Macintosh, Unix.
1718
1719
1720.. function:: WSTOPSIG(status)
1721
1722 Return the signal which caused the process to stop. Availability: Macintosh,
1723 Unix.
1724
1725
1726.. function:: WTERMSIG(status)
1727
1728 Return the signal which caused the process to exit. Availability: Macintosh,
1729 Unix.
1730
1731
1732.. _os-path:
1733
1734Miscellaneous System Information
1735--------------------------------
1736
1737
1738.. function:: confstr(name)
1739
1740 Return string-valued system configuration values. *name* specifies the
1741 configuration value to retrieve; it may be a string which is the name of a
1742 defined system value; these names are specified in a number of standards (POSIX,
1743 Unix 95, Unix 98, and others). Some platforms define additional names as well.
1744 The names known to the host operating system are given as the keys of the
1745 ``confstr_names`` dictionary. For configuration variables not included in that
1746 mapping, passing an integer for *name* is also accepted. Availability:
1747 Macintosh, Unix.
1748
1749 If the configuration value specified by *name* isn't defined, ``None`` is
1750 returned.
1751
1752 If *name* is a string and is not known, :exc:`ValueError` is raised. If a
1753 specific value for *name* is not supported by the host system, even if it is
1754 included in ``confstr_names``, an :exc:`OSError` is raised with
1755 :const:`errno.EINVAL` for the error number.
1756
1757
1758.. data:: confstr_names
1759
1760 Dictionary mapping names accepted by :func:`confstr` to the integer values
1761 defined for those names by the host operating system. This can be used to
1762 determine the set of names known to the system. Availability: Macintosh, Unix.
1763
1764
1765.. function:: getloadavg()
1766
1767 Return the number of processes in the system run queue averaged over the last 1,
1768 5, and 15 minutes or raises :exc:`OSError` if the load average was
1769 unobtainable.
1770
Georg Brandl116aa622007-08-15 14:28:22 +00001771
1772.. function:: sysconf(name)
1773
1774 Return integer-valued system configuration values. If the configuration value
1775 specified by *name* isn't defined, ``-1`` is returned. The comments regarding
1776 the *name* parameter for :func:`confstr` apply here as well; the dictionary that
1777 provides information on the known names is given by ``sysconf_names``.
1778 Availability: Macintosh, Unix.
1779
1780
1781.. data:: sysconf_names
1782
1783 Dictionary mapping names accepted by :func:`sysconf` to the integer values
1784 defined for those names by the host operating system. This can be used to
1785 determine the set of names known to the system. Availability: Macintosh, Unix.
1786
1787The follow data values are used to support path manipulation operations. These
1788are defined for all platforms.
1789
1790Higher-level operations on pathnames are defined in the :mod:`os.path` module.
1791
1792
1793.. data:: curdir
1794
1795 The constant string used by the operating system to refer to the current
1796 directory. For example: ``'.'`` for POSIX or ``':'`` for Mac OS 9. Also
1797 available via :mod:`os.path`.
1798
1799
1800.. data:: pardir
1801
1802 The constant string used by the operating system to refer to the parent
1803 directory. For example: ``'..'`` for POSIX or ``'::'`` for Mac OS 9. Also
1804 available via :mod:`os.path`.
1805
1806
1807.. data:: sep
1808
1809 The character used by the operating system to separate pathname components, for
1810 example, ``'/'`` for POSIX or ``':'`` for Mac OS 9. Note that knowing this is
1811 not sufficient to be able to parse or concatenate pathnames --- use
1812 :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
1813 useful. Also available via :mod:`os.path`.
1814
1815
1816.. data:: altsep
1817
1818 An alternative character used by the operating system to separate pathname
1819 components, or ``None`` if only one separator character exists. This is set to
1820 ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
1821 :mod:`os.path`.
1822
1823
1824.. data:: extsep
1825
1826 The character which separates the base filename from the extension; for example,
1827 the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.
1828
Georg Brandl116aa622007-08-15 14:28:22 +00001829
1830.. data:: pathsep
1831
1832 The character conventionally used by the operating system to separate search
1833 path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
1834 Windows. Also available via :mod:`os.path`.
1835
1836
1837.. data:: defpath
1838
1839 The default search path used by :func:`exec\*p\*` and :func:`spawn\*p\*` if the
1840 environment doesn't have a ``'PATH'`` key. Also available via :mod:`os.path`.
1841
1842
1843.. data:: linesep
1844
1845 The string used to separate (or, rather, terminate) lines on the current
1846 platform. This may be a single character, such as ``'\n'`` for POSIX or
1847 ``'\r'`` for Mac OS, or multiple characters, for example, ``'\r\n'`` for
1848 Windows. Do not use *os.linesep* as a line terminator when writing files opened
1849 in text mode (the default); use a single ``'\n'`` instead, on all platforms.
1850
1851
1852.. data:: devnull
1853
1854 The file path of the null device. For example: ``'/dev/null'`` for POSIX or
1855 ``'Dev:Nul'`` for Mac OS 9. Also available via :mod:`os.path`.
1856
Georg Brandl116aa622007-08-15 14:28:22 +00001857
1858.. _os-miscfunc:
1859
1860Miscellaneous Functions
1861-----------------------
1862
1863
1864.. function:: urandom(n)
1865
1866 Return a string of *n* random bytes suitable for cryptographic use.
1867
1868 This function returns random bytes from an OS-specific randomness source. The
1869 returned data should be unpredictable enough for cryptographic applications,
1870 though its exact quality depends on the OS implementation. On a UNIX-like
1871 system this will query /dev/urandom, and on Windows it will use CryptGenRandom.
1872 If a randomness source is not found, :exc:`NotImplementedError` will be raised.