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