PageRenderTime 62ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/Doc/library/os.rst

http://unladen-swallow.googlecode.com/
ReStructuredText | 2154 lines | 1376 code | 778 blank | 0 comment | 0 complexity | 3f385f38c7506dc5e3ab477140efda3d MD5 | raw file
Possible License(s): 0BSD, BSD-3-Clause
  1. :mod:`os` --- Miscellaneous operating system interfaces
  2. =======================================================
  3. .. module:: os
  4. :synopsis: Miscellaneous operating system interfaces.
  5. This module provides a portable way of using operating system dependent
  6. functionality. If you just want to read or write a file see :func:`open`, if
  7. you want to manipulate paths, see the :mod:`os.path` module, and if you want to
  8. read all the lines in all the files on the command line see the :mod:`fileinput`
  9. module. For creating temporary files and directories see the :mod:`tempfile`
  10. module, and for high-level file and directory handling see the :mod:`shutil`
  11. module.
  12. The design of all built-in operating system dependent modules of Python is such
  13. that as long as the same functionality is available, it uses the same interface;
  14. for example, the function ``os.stat(path)`` returns stat information about
  15. *path* in the same format (which happens to have originated with the POSIX
  16. interface).
  17. Extensions peculiar to a particular operating system are also available through
  18. the :mod:`os` module, but using them is of course a threat to portability!
  19. .. note::
  20. If not separately noted, all functions that claim "Availability: Unix" are
  21. supported on Mac OS X, which builds on a Unix core.
  22. .. note::
  23. All functions in this module raise :exc:`OSError` in the case of invalid or
  24. inaccessible file names and paths, or other arguments that have the correct
  25. type, but are not accepted by the operating system.
  26. .. exception:: error
  27. An alias for the built-in :exc:`OSError` exception.
  28. .. data:: name
  29. The name of the operating system dependent module imported. The following names
  30. have currently been registered: ``'posix'``, ``'nt'``, ``'mac'``, ``'os2'``,
  31. ``'ce'``, ``'java'``, ``'riscos'``.
  32. .. _os-procinfo:
  33. Process Parameters
  34. ------------------
  35. These functions and data items provide information and operate on the current
  36. process and user.
  37. .. data:: environ
  38. A mapping object representing the string environment. For example,
  39. ``environ['HOME']`` is the pathname of your home directory (on some platforms),
  40. and is equivalent to ``getenv("HOME")`` in C.
  41. This mapping is captured the first time the :mod:`os` module is imported,
  42. typically during Python startup as part of processing :file:`site.py`. Changes
  43. to the environment made after this time are not reflected in ``os.environ``,
  44. except for changes made by modifying ``os.environ`` directly.
  45. If the platform supports the :func:`putenv` function, this mapping may be used
  46. to modify the environment as well as query the environment. :func:`putenv` will
  47. be called automatically when the mapping is modified.
  48. .. note::
  49. Calling :func:`putenv` directly does not change ``os.environ``, so it's better
  50. to modify ``os.environ``.
  51. .. note::
  52. On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
  53. cause memory leaks. Refer to the system documentation for
  54. :cfunc:`putenv`.
  55. If :func:`putenv` is not provided, a modified copy of this mapping may be
  56. passed to the appropriate process-creation functions to cause child processes
  57. to use a modified environment.
  58. If the platform supports the :func:`unsetenv` function, you can delete items in
  59. this mapping to unset environment variables. :func:`unsetenv` will be called
  60. automatically when an item is deleted from ``os.environ``, and when
  61. one of the :meth:`pop` or :meth:`clear` methods is called.
  62. .. versionchanged:: 2.6
  63. Also unset environment variables when calling :meth:`os.environ.clear`
  64. and :meth:`os.environ.pop`.
  65. .. function:: chdir(path)
  66. fchdir(fd)
  67. getcwd()
  68. :noindex:
  69. These functions are described in :ref:`os-file-dir`.
  70. .. function:: ctermid()
  71. Return the filename corresponding to the controlling terminal of the process.
  72. Availability: Unix.
  73. .. function:: getegid()
  74. Return the effective group id of the current process. This corresponds to the
  75. "set id" bit on the file being executed in the current process. Availability:
  76. Unix.
  77. .. function:: geteuid()
  78. .. index:: single: user; effective id
  79. Return the current process's effective user id. Availability: Unix.
  80. .. function:: getgid()
  81. .. index:: single: process; group
  82. Return the real group id of the current process. Availability: Unix.
  83. .. function:: getgroups()
  84. Return list of supplemental group ids associated with the current process.
  85. Availability: Unix.
  86. .. function:: getlogin()
  87. Return the name of the user logged in on the controlling terminal of the
  88. process. For most purposes, it is more useful to use the environment variable
  89. :envvar:`LOGNAME` to find out who the user is, or
  90. ``pwd.getpwuid(os.getuid())[0]`` to get the login name of the currently
  91. effective user id. Availability: Unix.
  92. .. function:: getpgid(pid)
  93. Return the process group id of the process with process id *pid*. If *pid* is 0,
  94. the process group id of the current process is returned. Availability: Unix.
  95. .. versionadded:: 2.3
  96. .. function:: getpgrp()
  97. .. index:: single: process; group
  98. Return the id of the current process group. Availability: Unix.
  99. .. function:: getpid()
  100. .. index:: single: process; id
  101. Return the current process id. Availability: Unix, Windows.
  102. .. function:: getppid()
  103. .. index:: single: process; id of parent
  104. Return the parent's process id. Availability: Unix.
  105. .. function:: getuid()
  106. .. index:: single: user; id
  107. Return the current process's user id. Availability: Unix.
  108. .. function:: getenv(varname[, value])
  109. Return the value of the environment variable *varname* if it exists, or *value*
  110. if it doesn't. *value* defaults to ``None``. Availability: most flavors of
  111. Unix, Windows.
  112. .. function:: putenv(varname, value)
  113. .. index:: single: environment variables; setting
  114. Set the environment variable named *varname* to the string *value*. Such
  115. changes to the environment affect subprocesses started with :func:`os.system`,
  116. :func:`popen` or :func:`fork` and :func:`execv`. Availability: most flavors of
  117. Unix, Windows.
  118. .. note::
  119. On some platforms, including FreeBSD and Mac OS X, setting ``environ`` may
  120. cause memory leaks. Refer to the system documentation for putenv.
  121. When :func:`putenv` is supported, assignments to items in ``os.environ`` are
  122. automatically translated into corresponding calls to :func:`putenv`; however,
  123. calls to :func:`putenv` don't update ``os.environ``, so it is actually
  124. preferable to assign to items of ``os.environ``.
  125. .. function:: setegid(egid)
  126. Set the current process's effective group id. Availability: Unix.
  127. .. function:: seteuid(euid)
  128. Set the current process's effective user id. Availability: Unix.
  129. .. function:: setgid(gid)
  130. Set the current process' group id. Availability: Unix.
  131. .. function:: setgroups(groups)
  132. Set the list of supplemental group ids associated with the current process to
  133. *groups*. *groups* must be a sequence, and each element must be an integer
  134. identifying a group. This operation is typically available only to the superuser.
  135. Availability: Unix.
  136. .. versionadded:: 2.2
  137. .. function:: setpgrp()
  138. Call the system call :cfunc:`setpgrp` or :cfunc:`setpgrp(0, 0)` depending on
  139. which version is implemented (if any). See the Unix manual for the semantics.
  140. Availability: Unix.
  141. .. function:: setpgid(pid, pgrp)
  142. Call the system call :cfunc:`setpgid` to set the process group id of the
  143. process with id *pid* to the process group with id *pgrp*. See the Unix manual
  144. for the semantics. Availability: Unix.
  145. .. function:: setreuid(ruid, euid)
  146. Set the current process's real and effective user ids. Availability: Unix.
  147. .. function:: setregid(rgid, egid)
  148. Set the current process's real and effective group ids. Availability: Unix.
  149. .. function:: getsid(pid)
  150. Call the system call :cfunc:`getsid`. See the Unix manual for the semantics.
  151. Availability: Unix.
  152. .. versionadded:: 2.4
  153. .. function:: setsid()
  154. Call the system call :cfunc:`setsid`. See the Unix manual for the semantics.
  155. Availability: Unix.
  156. .. function:: setuid(uid)
  157. .. index:: single: user; id, setting
  158. Set the current process's user id. Availability: Unix.
  159. .. placed in this section since it relates to errno.... a little weak
  160. .. function:: strerror(code)
  161. Return the error message corresponding to the error code in *code*.
  162. On platforms where :cfunc:`strerror` returns ``NULL`` when given an unknown
  163. error number, :exc:`ValueError` is raised. Availability: Unix, Windows.
  164. .. function:: umask(mask)
  165. Set the current numeric umask and return the previous umask. Availability:
  166. Unix, Windows.
  167. .. function:: uname()
  168. .. index::
  169. single: gethostname() (in module socket)
  170. single: gethostbyaddr() (in module socket)
  171. Return a 5-tuple containing information identifying the current operating
  172. system. The tuple contains 5 strings: ``(sysname, nodename, release, version,
  173. machine)``. Some systems truncate the nodename to 8 characters or to the
  174. leading component; a better way to get the hostname is
  175. :func:`socket.gethostname` or even
  176. ``socket.gethostbyaddr(socket.gethostname())``. Availability: recent flavors of
  177. Unix.
  178. .. function:: unsetenv(varname)
  179. .. index:: single: environment variables; deleting
  180. Unset (delete) the environment variable named *varname*. Such changes to the
  181. environment affect subprocesses started with :func:`os.system`, :func:`popen` or
  182. :func:`fork` and :func:`execv`. Availability: most flavors of Unix, Windows.
  183. When :func:`unsetenv` is supported, deletion of items in ``os.environ`` is
  184. automatically translated into a corresponding call to :func:`unsetenv`; however,
  185. calls to :func:`unsetenv` don't update ``os.environ``, so it is actually
  186. preferable to delete items of ``os.environ``.
  187. .. _os-newstreams:
  188. File Object Creation
  189. --------------------
  190. These functions create new file objects. (See also :func:`open`.)
  191. .. function:: fdopen(fd[, mode[, bufsize]])
  192. .. index:: single: I/O control; buffering
  193. Return an open file object connected to the file descriptor *fd*. The *mode*
  194. and *bufsize* arguments have the same meaning as the corresponding arguments to
  195. the built-in :func:`open` function. Availability: Unix, Windows.
  196. .. versionchanged:: 2.3
  197. When specified, the *mode* argument must now start with one of the letters
  198. ``'r'``, ``'w'``, or ``'a'``, otherwise a :exc:`ValueError` is raised.
  199. .. versionchanged:: 2.5
  200. On Unix, when the *mode* argument starts with ``'a'``, the *O_APPEND* flag is
  201. set on the file descriptor (which the :cfunc:`fdopen` implementation already
  202. does on most platforms).
  203. .. function:: popen(command[, mode[, bufsize]])
  204. Open a pipe to or from *command*. The return value is an open file object
  205. connected to the pipe, which can be read or written depending on whether *mode*
  206. is ``'r'`` (default) or ``'w'``. The *bufsize* argument has the same meaning as
  207. the corresponding argument to the built-in :func:`open` function. The exit
  208. status of the command (encoded in the format specified for :func:`wait`) is
  209. available as the return value of the :meth:`~file.close` method of the file object,
  210. except that when the exit status is zero (termination without errors), ``None``
  211. is returned. Availability: Unix, Windows.
  212. .. deprecated:: 2.6
  213. This function is obsolete. Use the :mod:`subprocess` module. Check
  214. especially the :ref:`subprocess-replacements` section.
  215. .. versionchanged:: 2.0
  216. This function worked unreliably under Windows in earlier versions of Python.
  217. This was due to the use of the :cfunc:`_popen` function from the libraries
  218. provided with Windows. Newer versions of Python do not use the broken
  219. implementation from the Windows libraries.
  220. .. function:: tmpfile()
  221. Return a new file object opened in update mode (``w+b``). The file has no
  222. directory entries associated with it and will be automatically deleted once
  223. there are no file descriptors for the file. Availability: Unix,
  224. Windows.
  225. There are a number of different :func:`popen\*` functions that provide slightly
  226. different ways to create subprocesses.
  227. .. deprecated:: 2.6
  228. All of the :func:`popen\*` functions are obsolete. Use the :mod:`subprocess`
  229. module.
  230. For each of the :func:`popen\*` variants, if *bufsize* is specified, it
  231. specifies the buffer size for the I/O pipes. *mode*, if provided, should be the
  232. string ``'b'`` or ``'t'``; on Windows this is needed to determine whether the
  233. file objects should be opened in binary or text mode. The default value for
  234. *mode* is ``'t'``.
  235. Also, for each of these variants, on Unix, *cmd* may be a sequence, in which
  236. case arguments will be passed directly to the program without shell intervention
  237. (as with :func:`os.spawnv`). If *cmd* is a string it will be passed to the shell
  238. (as with :func:`os.system`).
  239. These methods do not make it possible to retrieve the exit status from the child
  240. processes. The only way to control the input and output streams and also
  241. retrieve the return codes is to use the :mod:`subprocess` module; these are only
  242. available on Unix.
  243. For a discussion of possible deadlock conditions related to the use of these
  244. functions, see :ref:`popen2-flow-control`.
  245. .. function:: popen2(cmd[, mode[, bufsize]])
  246. Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
  247. child_stdout)``.
  248. .. deprecated:: 2.6
  249. This function is obsolete. Use the :mod:`subprocess` module. Check
  250. especially the :ref:`subprocess-replacements` section.
  251. Availability: Unix, Windows.
  252. .. versionadded:: 2.0
  253. .. function:: popen3(cmd[, mode[, bufsize]])
  254. Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
  255. child_stdout, child_stderr)``.
  256. .. deprecated:: 2.6
  257. This function is obsolete. Use the :mod:`subprocess` module. Check
  258. especially the :ref:`subprocess-replacements` section.
  259. Availability: Unix, Windows.
  260. .. versionadded:: 2.0
  261. .. function:: popen4(cmd[, mode[, bufsize]])
  262. Execute *cmd* as a sub-process and return the file objects ``(child_stdin,
  263. child_stdout_and_stderr)``.
  264. .. deprecated:: 2.6
  265. This function is obsolete. Use the :mod:`subprocess` module. Check
  266. especially the :ref:`subprocess-replacements` section.
  267. Availability: Unix, Windows.
  268. .. versionadded:: 2.0
  269. (Note that ``child_stdin, child_stdout, and child_stderr`` are named from the
  270. point of view of the child process, so *child_stdin* is the child's standard
  271. input.)
  272. This functionality is also available in the :mod:`popen2` module using functions
  273. of the same names, but the return values of those functions have a different
  274. order.
  275. .. _os-fd-ops:
  276. File Descriptor Operations
  277. --------------------------
  278. These functions operate on I/O streams referenced using file descriptors.
  279. File descriptors are small integers corresponding to a file that has been opened
  280. by the current process. For example, standard input is usually file descriptor
  281. 0, standard output is 1, and standard error is 2. Further files opened by a
  282. process will then be assigned 3, 4, 5, and so forth. The name "file descriptor"
  283. is slightly deceptive; on Unix platforms, sockets and pipes are also referenced
  284. by file descriptors.
  285. .. function:: close(fd)
  286. Close file descriptor *fd*. Availability: Unix, Windows.
  287. .. note::
  288. This function is intended for low-level I/O and must be applied to a file
  289. descriptor as returned by :func:`os.open` or :func:`pipe`. To close a "file
  290. object" returned by the built-in function :func:`open` or by :func:`popen` or
  291. :func:`fdopen`, use its :meth:`~file.close` method.
  292. .. function:: closerange(fd_low, fd_high)
  293. Close all file descriptors from *fd_low* (inclusive) to *fd_high* (exclusive),
  294. ignoring errors. Availability: Unix, Windows. Equivalent to::
  295. for fd in xrange(fd_low, fd_high):
  296. try:
  297. os.close(fd)
  298. except OSError:
  299. pass
  300. .. versionadded:: 2.6
  301. .. function:: dup(fd)
  302. Return a duplicate of file descriptor *fd*. Availability: Unix,
  303. Windows.
  304. .. function:: dup2(fd, fd2)
  305. Duplicate file descriptor *fd* to *fd2*, closing the latter first if necessary.
  306. Availability: Unix, Windows.
  307. .. function:: fchmod(fd, mode)
  308. Change the mode of the file given by *fd* to the numeric *mode*. See the docs
  309. for :func:`chmod` for possible values of *mode*. Availability: Unix.
  310. .. versionadded:: 2.6
  311. .. function:: fchown(fd, uid, gid)
  312. Change the owner and group id of the file given by *fd* to the numeric *uid*
  313. and *gid*. To leave one of the ids unchanged, set it to -1.
  314. Availability: Unix.
  315. .. versionadded:: 2.6
  316. .. function:: fdatasync(fd)
  317. Force write of file with filedescriptor *fd* to disk. Does not force update of
  318. metadata. Availability: Unix.
  319. .. function:: fpathconf(fd, name)
  320. Return system configuration information relevant to an open file. *name*
  321. specifies the configuration value to retrieve; it may be a string which is the
  322. name of a defined system value; these names are specified in a number of
  323. standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
  324. additional names as well. The names known to the host operating system are
  325. given in the ``pathconf_names`` dictionary. For configuration variables not
  326. included in that mapping, passing an integer for *name* is also accepted.
  327. Availability: Unix.
  328. If *name* is a string and is not known, :exc:`ValueError` is raised. If a
  329. specific value for *name* is not supported by the host system, even if it is
  330. included in ``pathconf_names``, an :exc:`OSError` is raised with
  331. :const:`errno.EINVAL` for the error number.
  332. .. function:: fstat(fd)
  333. Return status for file descriptor *fd*, like :func:`stat`. Availability:
  334. Unix, Windows.
  335. .. function:: fstatvfs(fd)
  336. Return information about the filesystem containing the file associated with file
  337. descriptor *fd*, like :func:`statvfs`. Availability: Unix.
  338. .. function:: fsync(fd)
  339. Force write of file with filedescriptor *fd* to disk. On Unix, this calls the
  340. native :cfunc:`fsync` function; on Windows, the MS :cfunc:`_commit` function.
  341. If you're starting with a Python file object *f*, first do ``f.flush()``, and
  342. then do ``os.fsync(f.fileno())``, to ensure that all internal buffers associated
  343. with *f* are written to disk. Availability: Unix, and Windows
  344. starting in 2.2.3.
  345. .. function:: ftruncate(fd, length)
  346. Truncate the file corresponding to file descriptor *fd*, so that it is at most
  347. *length* bytes in size. Availability: Unix.
  348. .. function:: isatty(fd)
  349. Return ``True`` if the file descriptor *fd* is open and connected to a
  350. tty(-like) device, else ``False``. Availability: Unix.
  351. .. function:: lseek(fd, pos, how)
  352. Set the current position of file descriptor *fd* to position *pos*, modified
  353. by *how*: :const:`SEEK_SET` or ``0`` to set the position relative to the
  354. beginning of the file; :const:`SEEK_CUR` or ``1`` to set it relative to the
  355. current position; :const:`os.SEEK_END` or ``2`` to set it relative to the end of
  356. the file. Availability: Unix, Windows.
  357. .. function:: open(file, flags[, mode])
  358. Open the file *file* and set various flags according to *flags* and possibly its
  359. mode according to *mode*. The default *mode* is ``0777`` (octal), and the
  360. current umask value is first masked out. Return the file descriptor for the
  361. newly opened file. Availability: Unix, Windows.
  362. For a description of the flag and mode values, see the C run-time documentation;
  363. flag constants (like :const:`O_RDONLY` and :const:`O_WRONLY`) are defined in
  364. this module too (see below).
  365. .. note::
  366. This function is intended for low-level I/O. For normal usage, use the built-in
  367. function :func:`open`, which returns a "file object" with :meth:`~file.read` and
  368. :meth:`~file.write` methods (and many more). To wrap a file descriptor in a "file
  369. object", use :func:`fdopen`.
  370. .. function:: openpty()
  371. .. index:: module: pty
  372. Open a new pseudo-terminal pair. Return a pair of file descriptors ``(master,
  373. slave)`` for the pty and the tty, respectively. For a (slightly) more portable
  374. approach, use the :mod:`pty` module. Availability: some flavors of
  375. Unix.
  376. .. function:: pipe()
  377. Create a pipe. Return a pair of file descriptors ``(r, w)`` usable for reading
  378. and writing, respectively. Availability: Unix, Windows.
  379. .. function:: read(fd, n)
  380. Read at most *n* bytes from file descriptor *fd*. Return a string containing the
  381. bytes read. If the end of the file referred to by *fd* has been reached, an
  382. empty string is returned. Availability: Unix, Windows.
  383. .. note::
  384. This function is intended for low-level I/O and must be applied to a file
  385. descriptor as returned by :func:`os.open` or :func:`pipe`. To read a "file object"
  386. returned by the built-in function :func:`open` or by :func:`popen` or
  387. :func:`fdopen`, or :data:`sys.stdin`, use its :meth:`~file.read` or
  388. :meth:`~file.readline` methods.
  389. .. function:: tcgetpgrp(fd)
  390. Return the process group associated with the terminal given by *fd* (an open
  391. file descriptor as returned by :func:`os.open`). Availability: Unix.
  392. .. function:: tcsetpgrp(fd, pg)
  393. Set the process group associated with the terminal given by *fd* (an open file
  394. descriptor as returned by :func:`os.open`) to *pg*. Availability: Unix.
  395. .. function:: ttyname(fd)
  396. Return a string which specifies the terminal device associated with
  397. file descriptor *fd*. If *fd* is not associated with a terminal device, an
  398. exception is raised. Availability: Unix.
  399. .. function:: write(fd, str)
  400. Write the string *str* to file descriptor *fd*. Return the number of bytes
  401. actually written. Availability: Unix, Windows.
  402. .. note::
  403. This function is intended for low-level I/O and must be applied to a file
  404. descriptor as returned by :func:`os.open` or :func:`pipe`. To write a "file
  405. object" returned by the built-in function :func:`open` or by :func:`popen` or
  406. :func:`fdopen`, or :data:`sys.stdout` or :data:`sys.stderr`, use its
  407. :meth:`~file.write` method.
  408. The following constants are options for the *flags* parameter to the
  409. :func:`~os.open` function. They can be combined using the bitwise OR operator
  410. ``|``. Some of them are not available on all platforms. For descriptions of
  411. their availability and use, consult the :manpage:`open(2)` manual page on Unix
  412. or `the MSDN <http://msdn.microsoft.com/en-us/library/z0kc8e3z.aspx>`_ on Windows.
  413. .. data:: O_RDONLY
  414. O_WRONLY
  415. O_RDWR
  416. O_APPEND
  417. O_CREAT
  418. O_EXCL
  419. O_TRUNC
  420. These constants are available on Unix and Windows.
  421. .. data:: O_DSYNC
  422. O_RSYNC
  423. O_SYNC
  424. O_NDELAY
  425. O_NONBLOCK
  426. O_NOCTTY
  427. O_SHLOCK
  428. O_EXLOCK
  429. These constants are only available on Unix.
  430. .. data:: O_BINARY
  431. O_NOINHERIT
  432. O_SHORT_LIVED
  433. O_TEMPORARY
  434. O_RANDOM
  435. O_SEQUENTIAL
  436. O_TEXT
  437. These constants are only available on Windows.
  438. .. data:: O_ASYNC
  439. O_DIRECT
  440. O_DIRECTORY
  441. O_NOFOLLOW
  442. O_NOATIME
  443. These constants are GNU extensions and not present if they are not defined by
  444. the C library.
  445. .. data:: SEEK_SET
  446. SEEK_CUR
  447. SEEK_END
  448. Parameters to the :func:`lseek` function. Their values are 0, 1, and 2,
  449. respectively. Availability: Windows, Unix.
  450. .. versionadded:: 2.5
  451. .. _os-file-dir:
  452. Files and Directories
  453. ---------------------
  454. .. function:: access(path, mode)
  455. Use the real uid/gid to test for access to *path*. Note that most operations
  456. will use the effective uid/gid, therefore this routine can be used in a
  457. suid/sgid environment to test if the invoking user has the specified access to
  458. *path*. *mode* should be :const:`F_OK` to test the existence of *path*, or it
  459. can be the inclusive OR of one or more of :const:`R_OK`, :const:`W_OK`, and
  460. :const:`X_OK` to test permissions. Return :const:`True` if access is allowed,
  461. :const:`False` if not. See the Unix man page :manpage:`access(2)` for more
  462. information. Availability: Unix, Windows.
  463. .. note::
  464. Using :func:`access` to check if a user is authorized to e.g. open a file before
  465. actually doing so using :func:`open` creates a security hole, because the user
  466. might exploit the short time interval between checking and opening the file to
  467. manipulate it.
  468. .. note::
  469. I/O operations may fail even when :func:`access` indicates that they would
  470. succeed, particularly for operations on network filesystems which may have
  471. permissions semantics beyond the usual POSIX permission-bit model.
  472. .. data:: F_OK
  473. Value to pass as the *mode* parameter of :func:`access` to test the existence of
  474. *path*.
  475. .. data:: R_OK
  476. Value to include in the *mode* parameter of :func:`access` to test the
  477. readability of *path*.
  478. .. data:: W_OK
  479. Value to include in the *mode* parameter of :func:`access` to test the
  480. writability of *path*.
  481. .. data:: X_OK
  482. Value to include in the *mode* parameter of :func:`access` to determine if
  483. *path* can be executed.
  484. .. function:: chdir(path)
  485. .. index:: single: directory; changing
  486. Change the current working directory to *path*. Availability: Unix,
  487. Windows.
  488. .. function:: fchdir(fd)
  489. Change the current working directory to the directory represented by the file
  490. descriptor *fd*. The descriptor must refer to an opened directory, not an open
  491. file. Availability: Unix.
  492. .. versionadded:: 2.3
  493. .. function:: getcwd()
  494. Return a string representing the current working directory. Availability:
  495. Unix, Windows.
  496. .. function:: getcwdu()
  497. Return a Unicode object representing the current working directory.
  498. Availability: Unix, Windows.
  499. .. versionadded:: 2.3
  500. .. function:: chflags(path, flags)
  501. Set the flags of *path* to the numeric *flags*. *flags* may take a combination
  502. (bitwise OR) of the following values (as defined in the :mod:`stat` module):
  503. * ``UF_NODUMP``
  504. * ``UF_IMMUTABLE``
  505. * ``UF_APPEND``
  506. * ``UF_OPAQUE``
  507. * ``UF_NOUNLINK``
  508. * ``SF_ARCHIVED``
  509. * ``SF_IMMUTABLE``
  510. * ``SF_APPEND``
  511. * ``SF_NOUNLINK``
  512. * ``SF_SNAPSHOT``
  513. Availability: Unix.
  514. .. versionadded:: 2.6
  515. .. function:: chroot(path)
  516. Change the root directory of the current process to *path*. Availability:
  517. Unix.
  518. .. versionadded:: 2.2
  519. .. function:: chmod(path, mode)
  520. Change the mode of *path* to the numeric *mode*. *mode* may take one of the
  521. following values (as defined in the :mod:`stat` module) or bitwise ORed
  522. combinations of them:
  523. * :data:`stat.S_ISUID`
  524. * :data:`stat.S_ISGID`
  525. * :data:`stat.S_ENFMT`
  526. * :data:`stat.S_ISVTX`
  527. * :data:`stat.S_IREAD`
  528. * :data:`stat.S_IWRITE`
  529. * :data:`stat.S_IEXEC`
  530. * :data:`stat.S_IRWXU`
  531. * :data:`stat.S_IRUSR`
  532. * :data:`stat.S_IWUSR`
  533. * :data:`stat.S_IXUSR`
  534. * :data:`stat.S_IRWXG`
  535. * :data:`stat.S_IRGRP`
  536. * :data:`stat.S_IWGRP`
  537. * :data:`stat.S_IXGRP`
  538. * :data:`stat.S_IRWXO`
  539. * :data:`stat.S_IROTH`
  540. * :data:`stat.S_IWOTH`
  541. * :data:`stat.S_IXOTH`
  542. Availability: Unix, Windows.
  543. .. note::
  544. Although Windows supports :func:`chmod`, you can only set the file's read-only
  545. flag with it (via the ``stat.S_IWRITE`` and ``stat.S_IREAD``
  546. constants or a corresponding integer value). All other bits are
  547. ignored.
  548. .. function:: chown(path, uid, gid)
  549. Change the owner and group id of *path* to the numeric *uid* and *gid*. To leave
  550. one of the ids unchanged, set it to -1. Availability: Unix.
  551. .. function:: lchflags(path, flags)
  552. Set the flags of *path* to the numeric *flags*, like :func:`chflags`, but do not
  553. follow symbolic links. Availability: Unix.
  554. .. versionadded:: 2.6
  555. .. function:: lchmod(path, mode)
  556. Change the mode of *path* to the numeric *mode*. If path is a symlink, this
  557. affects the symlink rather than the target. See the docs for :func:`chmod`
  558. for possible values of *mode*. Availability: Unix.
  559. .. versionadded:: 2.6
  560. .. function:: lchown(path, uid, gid)
  561. Change the owner and group id of *path* to the numeric *uid* and *gid*. This
  562. function will not follow symbolic links. Availability: Unix.
  563. .. versionadded:: 2.3
  564. .. function:: link(src, dst)
  565. Create a hard link pointing to *src* named *dst*. Availability: Unix.
  566. .. function:: listdir(path)
  567. Return a list containing the names of the entries in the directory given by
  568. *path*. The list is in arbitrary order. It does not include the special
  569. entries ``'.'`` and ``'..'`` even if they are present in the
  570. directory. Availability: Unix, Windows.
  571. .. versionchanged:: 2.3
  572. On Windows NT/2k/XP and Unix, if *path* is a Unicode object, the result will be
  573. a list of Unicode objects. Undecodable filenames will still be returned as
  574. string objects.
  575. .. function:: lstat(path)
  576. Like :func:`stat`, but do not follow symbolic links. This is an alias for
  577. :func:`stat` on platforms that do not support symbolic links, such as
  578. Windows.
  579. .. function:: mkfifo(path[, mode])
  580. Create a FIFO (a named pipe) named *path* with numeric mode *mode*. The default
  581. *mode* is ``0666`` (octal). The current umask value is first masked out from
  582. the mode. Availability: Unix.
  583. FIFOs are pipes that can be accessed like regular files. FIFOs exist until they
  584. are deleted (for example with :func:`os.unlink`). Generally, FIFOs are used as
  585. rendezvous between "client" and "server" type processes: the server opens the
  586. FIFO for reading, and the client opens it for writing. Note that :func:`mkfifo`
  587. doesn't open the FIFO --- it just creates the rendezvous point.
  588. .. function:: mknod(filename[, mode=0600, device])
  589. Create a filesystem node (file, device special file or named pipe) named
  590. *filename*. *mode* specifies both the permissions to use and the type of node to
  591. be created, being combined (bitwise OR) with one of ``stat.S_IFREG``,
  592. ``stat.S_IFCHR``, ``stat.S_IFBLK``,
  593. and ``stat.S_IFIFO`` (those constants are available in :mod:`stat`).
  594. For ``stat.S_IFCHR`` and
  595. ``stat.S_IFBLK``, *device* defines the newly created device special file (probably using
  596. :func:`os.makedev`), otherwise it is ignored.
  597. .. versionadded:: 2.3
  598. .. function:: major(device)
  599. Extract the device major number from a raw device number (usually the
  600. :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
  601. .. versionadded:: 2.3
  602. .. function:: minor(device)
  603. Extract the device minor number from a raw device number (usually the
  604. :attr:`st_dev` or :attr:`st_rdev` field from :ctype:`stat`).
  605. .. versionadded:: 2.3
  606. .. function:: makedev(major, minor)
  607. Compose a raw device number from the major and minor device numbers.
  608. .. versionadded:: 2.3
  609. .. function:: mkdir(path[, mode])
  610. Create a directory named *path* with numeric mode *mode*. The default *mode* is
  611. ``0777`` (octal). On some systems, *mode* is ignored. Where it is used, the
  612. current umask value is first masked out. Availability: Unix, Windows.
  613. It is also possible to create temporary directories; see the
  614. :mod:`tempfile` module's :func:`tempfile.mkdtemp` function.
  615. .. function:: makedirs(path[, mode])
  616. .. index::
  617. single: directory; creating
  618. single: UNC paths; and os.makedirs()
  619. Recursive directory creation function. Like :func:`mkdir`, but makes all
  620. intermediate-level directories needed to contain the leaf directory. Throws an
  621. :exc:`error` exception if the leaf directory already exists or cannot be
  622. created. The default *mode* is ``0777`` (octal). On some systems, *mode* is
  623. ignored. Where it is used, the current umask value is first masked out.
  624. .. note::
  625. :func:`makedirs` will become confused if the path elements to create include
  626. :data:`os.pardir`.
  627. .. versionadded:: 1.5.2
  628. .. versionchanged:: 2.3
  629. This function now handles UNC paths correctly.
  630. .. function:: pathconf(path, name)
  631. Return system configuration information relevant to a named file. *name*
  632. specifies the configuration value to retrieve; it may be a string which is the
  633. name of a defined system value; these names are specified in a number of
  634. standards (POSIX.1, Unix 95, Unix 98, and others). Some platforms define
  635. additional names as well. The names known to the host operating system are
  636. given in the ``pathconf_names`` dictionary. For configuration variables not
  637. included in that mapping, passing an integer for *name* is also accepted.
  638. Availability: Unix.
  639. If *name* is a string and is not known, :exc:`ValueError` is raised. If a
  640. specific value for *name* is not supported by the host system, even if it is
  641. included in ``pathconf_names``, an :exc:`OSError` is raised with
  642. :const:`errno.EINVAL` for the error number.
  643. .. data:: pathconf_names
  644. Dictionary mapping names accepted by :func:`pathconf` and :func:`fpathconf` to
  645. the integer values defined for those names by the host operating system. This
  646. can be used to determine the set of names known to the system. Availability:
  647. Unix.
  648. .. function:: readlink(path)
  649. Return a string representing the path to which the symbolic link points. The
  650. result may be either an absolute or relative pathname; if it is relative, it may
  651. be converted to an absolute pathname using ``os.path.join(os.path.dirname(path),
  652. result)``.
  653. .. versionchanged:: 2.6
  654. If the *path* is a Unicode object the result will also be a Unicode object.
  655. Availability: Unix.
  656. .. function:: remove(path)
  657. Remove the file *path*. If *path* is a directory, :exc:`OSError` is raised; see
  658. :func:`rmdir` below to remove a directory. This is identical to the
  659. :func:`unlink` function documented below. On Windows, attempting to remove a
  660. file that is in use causes an exception to be raised; on Unix, the directory
  661. entry is removed but the storage allocated to the file is not made available
  662. until the original file is no longer in use. Availability: Unix,
  663. Windows.
  664. .. function:: removedirs(path)
  665. .. index:: single: directory; deleting
  666. Remove directories recursively. Works like :func:`rmdir` except that, if the
  667. leaf directory is successfully removed, :func:`removedirs` tries to
  668. successively remove every parent directory mentioned in *path* until an error
  669. is raised (which is ignored, because it generally means that a parent directory
  670. is not empty). For example, ``os.removedirs('foo/bar/baz')`` will first remove
  671. the directory ``'foo/bar/baz'``, and then remove ``'foo/bar'`` and ``'foo'`` if
  672. they are empty. Raises :exc:`OSError` if the leaf directory could not be
  673. successfully removed.
  674. .. versionadded:: 1.5.2
  675. .. function:: rename(src, dst)
  676. Rename the file or directory *src* to *dst*. If *dst* is a directory,
  677. :exc:`OSError` will be raised. On Unix, if *dst* exists and is a file, it will
  678. be replaced silently if the user has permission. The operation may fail on some
  679. Unix flavors if *src* and *dst* are on different filesystems. If successful,
  680. the renaming will be an atomic operation (this is a POSIX requirement). On
  681. Windows, if *dst* already exists, :exc:`OSError` will be raised even if it is a
  682. file; there may be no way to implement an atomic rename when *dst* names an
  683. existing file. Availability: Unix, Windows.
  684. .. function:: renames(old, new)
  685. Recursive directory or file renaming function. Works like :func:`rename`, except
  686. creation of any intermediate directories needed to make the new pathname good is
  687. attempted first. After the rename, directories corresponding to rightmost path
  688. segments of the old name will be pruned away using :func:`removedirs`.
  689. .. versionadded:: 1.5.2
  690. .. note::
  691. This function can fail with the new directory structure made if you lack
  692. permissions needed to remove the leaf directory or file.
  693. .. function:: rmdir(path)
  694. Remove the directory *path*. Availability: Unix, Windows.
  695. .. function:: stat(path)
  696. Perform a :cfunc:`stat` system call on the given path. The return value is an
  697. object whose attributes correspond to the members of the :ctype:`stat`
  698. structure, namely: :attr:`st_mode` (protection bits), :attr:`st_ino` (inode
  699. number), :attr:`st_dev` (device), :attr:`st_nlink` (number of hard links),
  700. :attr:`st_uid` (user id of owner), :attr:`st_gid` (group id of owner),
  701. :attr:`st_size` (size of file, in bytes), :attr:`st_atime` (time of most recent
  702. access), :attr:`st_mtime` (time of most recent content modification),
  703. :attr:`st_ctime` (platform dependent; time of most recent metadata change on
  704. Unix, or the time of creation on Windows)::
  705. >>> import os
  706. >>> statinfo = os.stat('somefile.txt')
  707. >>> statinfo
  708. (33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
  709. >>> statinfo.st_size
  710. 926L
  711. >>>
  712. .. versionchanged:: 2.3
  713. If :func:`stat_float_times` returns ``True``, the time values are floats, measuring
  714. seconds. Fractions of a second may be reported if the system supports that. On
  715. Mac OS, the times are always floats. See :func:`stat_float_times` for further
  716. discussion.
  717. On some Unix systems (such as Linux), the following attributes may also be
  718. available: :attr:`st_blocks` (number of blocks allocated for file),
  719. :attr:`st_blksize` (filesystem blocksize), :attr:`st_rdev` (type of device if an
  720. inode device). :attr:`st_flags` (user defined flags for file).
  721. On other Unix systems (such as FreeBSD), the following attributes may be
  722. available (but may be only filled out if root tries to use them): :attr:`st_gen`
  723. (file generation number), :attr:`st_birthtime` (time of file creation).
  724. On Mac OS systems, the following attributes may also be available:
  725. :attr:`st_rsize`, :attr:`st_creator`, :attr:`st_type`.
  726. On RISCOS systems, the following attributes are also available: :attr:`st_ftype`
  727. (file type), :attr:`st_attrs` (attributes), :attr:`st_obtype` (object type).
  728. .. index:: module: stat
  729. For backward compatibility, the return value of :func:`stat` is also accessible
  730. as a tuple of at least 10 integers giving the most important (and portable)
  731. members of the :ctype:`stat` structure, in the order :attr:`st_mode`,
  732. :attr:`st_ino`, :attr:`st_dev`, :attr:`st_nlink`, :attr:`st_uid`,
  733. :attr:`st_gid`, :attr:`st_size`, :attr:`st_atime`, :attr:`st_mtime`,
  734. :attr:`st_ctime`. More items may be added at the end by some implementations.
  735. The standard module :mod:`stat` defines functions and constants that are useful
  736. for extracting information from a :ctype:`stat` structure. (On Windows, some
  737. items are filled with dummy values.)
  738. .. note::
  739. The exact meaning and resolution of the :attr:`st_atime`, :attr:`st_mtime`, and
  740. :attr:`st_ctime` members depends on the operating system and the file system.
  741. For example, on Windows systems using the FAT or FAT32 file systems,
  742. :attr:`st_mtime` has 2-second resolution, and :attr:`st_atime` has only 1-day
  743. resolution. See your operating system documentation for details.
  744. Availability: Unix, Windows.
  745. .. versionchanged:: 2.2
  746. Added access to values as attributes of the returned object.
  747. .. versionchanged:: 2.5
  748. Added :attr:`st_gen` and :attr:`st_birthtime`.
  749. .. function:: stat_float_times([newvalue])
  750. Determine whether :class:`stat_result` represents time stamps as float objects.
  751. If *newvalue* is ``True``, future calls to :func:`stat` return floats, if it is
  752. ``False``, future calls return ints. If *newvalue* is omitted, return the
  753. current setting.
  754. For compatibility with older Python versions, accessing :class:`stat_result` as
  755. a tuple always returns integers.
  756. .. versionchanged:: 2.5
  757. Python now returns float values by default. Applications which do not work
  758. correctly with floating point time stamps can use this function to restore the
  759. old behaviour.
  760. The resolution of the timestamps (that is the smallest possible fraction)
  761. depends on the system. Some systems only support second resolution; on these
  762. systems, the fraction will always be zero.
  763. It is recommended that this setting is only changed at program startup time in
  764. the *__main__* module; libraries should never change this setting. If an
  765. application uses a library that works incorrectly if floating point time stamps
  766. are processed, this application should turn the feature off until the library
  767. has been corrected.
  768. .. function:: statvfs(path)
  769. Perform a :cfunc:`statvfs` system call on the given path. The return value is
  770. an object whose attributes describe the filesystem on the given path, and
  771. correspond to the members of the :ctype:`statvfs` structure, namely:
  772. :attr:`f_bsize`, :attr:`f_frsize`, :attr:`f_blocks`, :attr:`f_bfree`,
  773. :attr:`f_bavail`, :attr:`f_files`, :attr:`f_ffree`, :attr:`f_favail`,
  774. :attr:`f_flag`, :attr:`f_namemax`. Availability: Unix.
  775. .. index:: module: statvfs
  776. For backward compatibility, the return value is also accessible as a tuple whose
  777. values correspond to the attributes, in the order given above. The standard
  778. module :mod:`statvfs` defines constants that are useful for extracting
  779. information from a :ctype:`statvfs` structure when accessing it as a sequence;
  780. this remains useful when writing code that needs to work with versions of Python
  781. that don't support accessing the fields as attributes.
  782. .. versionchanged:: 2.2
  783. Added access to values as attributes of the returned object.
  784. .. function:: symlink(src, dst)
  785. Create a symbolic link pointing to *src* named *dst*. Availability: Unix.
  786. .. function:: tempnam([dir[, prefix]])
  787. Return a unique path name that is reasonable for creating a temporary file.
  788. This will be an absolute path that names a potential directory entry in the
  789. directory *dir* or a common location for temporary files if *dir* is omitted or
  790. ``None``. If given and not ``None``, *prefix* is used to provide a short prefix
  791. to the filename. Applications are responsible for properly creating and
  792. managing files created using paths returned by :func:`tempnam`; no automatic
  793. cleanup is provided. On Unix, the environment variable :envvar:`TMPDIR`
  794. overrides *dir*, while on Windows :envvar:`TMP` is used. The specific
  795. behavior of this function depends on the C library implementation; some aspects
  796. are underspecified in system documentation.
  797. .. warning::
  798. Use of :func:`tempnam` is vulnerable to symlink attacks; consider using
  799. :func:`tmpfile` (section :ref:`os-newstreams`) instead.
  800. Availability: Unix, Windows.
  801. .. function:: tmpnam()
  802. Return a unique path name that is reasonable for creating a temporary file.
  803. This will be an absolute path that names a potential directory entry in a common
  804. location for temporary files. Applications are responsible for properly
  805. creating and managing files created using paths returned by :func:`tmpnam`; no
  806. automatic cleanup is provided.
  807. .. warning::
  808. Use of :func:`tmpnam` is vulnerable to symlink attacks; consider using
  809. :func:`tmpfile` (section :ref:`os-newstreams`) instead.
  810. Availability: Unix, Windows. This function probably shouldn't be used on
  811. Windows, though: Microsoft's implementation of :func:`tmpnam` always creates a
  812. name in the root directory of the current drive, and that's generally a poor
  813. location for a temp file (depending on privileges, you may not even be able to
  814. open a file using this name).
  815. .. data:: TMP_MAX
  816. The maximum number of unique names that :func:`tmpnam` will generate before
  817. reusing names.
  818. .. function:: unlink(path)
  819. Remove the file *path*. This is the same function as :func:`remove`; the
  820. :func:`unlink` name is its traditional Unix name. Availability: Unix,
  821. Windows.
  822. .. function:: utime(path, times)
  823. Set the access and modified times of the file specified by *path*. If *times*
  824. is ``None``, then the file's access and modified times are set to the current
  825. time. (The effect is similar to running the Unix program :program:`touch` on
  826. the path.) Otherwise, *times* must be a 2-tuple of numbers, of the form
  827. ``(atime, mtime)`` which is used to set the access and modified times,
  828. respectively. Whether a directory can be given for *path* depends on whether
  829. the operating system implements directories as files (for example, Windows
  830. does not). Note that the exact times you set here may not be returned by a
  831. subsequent :func:`stat` call, depending on the resolution with which your
  832. operating system records access and modification times; see :func:`stat`.
  833. .. versionchanged:: 2.0
  834. Added support for ``None`` for *times*.
  835. Availability: Unix, Windows.
  836. .. function:: walk(top[, topdown=True [, onerror=None[, followlinks=False]]])
  837. .. index::
  838. single: directory; walking
  839. single: directory; traversal
  840. Generate the file names in a directory tree by walking the tree
  841. either top-down or bottom-up. For each directory in the tree rooted at directory
  842. *top* (including *top* itself), it yields a 3-tuple ``(dirpath, dirnames,
  843. filenames)``.
  844. *dirpath* is a string, the path to the directory. *dirnames* is a list of the
  845. names of the subdirectories in *dirpath* (excluding ``'.'`` and ``'..'``).
  846. *filenames* is a list of the names of the non-directory files in *dirpath*.
  847. Note that the names in the lists contain no path components. To get a full path
  848. (which begins with *top*) to a file or directory in *dirpath*, do
  849. ``os.path.join(dirpath, name)``.
  850. If optional argument *topdown* is ``True`` or not specified, the triple for a
  851. directory is generated before the triples for any of its subdirectories
  852. (directories are generated top-down). If *topdown* is ``False``, the triple for a
  853. directory is generated after the triples for all of its subdirectories
  854. (directories are generated bottom-up).
  855. When *topdown* is ``True``, the caller can modify the *dirnames* list in-place
  856. (perhaps using :keyword:`del` or slice assignment), and :func:`walk` will only
  857. recurse into the subdirectories whose names remain in *dirnames*; this can be
  858. used to prune the search, impose a specific order of visiting, or even to inform
  859. :func:`walk` about directories the caller creates or renames before it resumes
  860. :func:`walk` again. Modifying *dirnames* when *topdown* is ``False`` is
  861. ineffective, because in bottom-up mode the directories in *dirnames* are
  862. generated before *dirpath* itself is generated.
  863. By default errors from the :func:`listdir` call are ignored. If optional
  864. argument *onerror* is specified, it should be a function; it will be called with
  865. one argument, an :exc:`OSError` instance. It can report the error to continue
  866. with the walk, or raise the exception to abort the walk. Note that the filename
  867. is available as the ``filename`` attribute of the exception object.
  868. By default, :func:`walk` will not walk down into symbolic links that resolve to
  869. directories. Set *followlinks* to ``True`` to visit directories pointed to by
  870. symlinks, on systems that support them.
  871. .. versionadded:: 2.6
  872. The *followlinks* parameter.
  873. .. note::
  874. Be aware that setting *followlinks* to ``True`` can lead to infinite recursion if a
  875. link points to a parent directory of itself. :func:`walk` does not keep track of
  876. the directories it visited already.
  877. .. note::
  878. If you pass a relative pathname, don't change the current working directory
  879. between resumptions of :func:`walk`. :func:`walk` never changes the current
  880. directory, and assumes that its caller doesn't either.
  881. This example displays the number of bytes taken by non-directory files in each
  882. directory under the starting directory, except that it doesn't look under any
  883. CVS subdirectory::
  884. import os
  885. from os.path import join, getsize
  886. for root, dirs, files in os.walk('python/Lib/email'):
  887. print root, "consumes",
  888. print sum(getsize(join(root, name)) for name in files),
  889. print "bytes in", len(files), "non-directory files"
  890. if 'CVS' in dirs:
  891. dirs.remove('CVS') # don't visit CVS directories
  892. In the next example, walking the tree bottom-up is essential: :func:`rmdir`
  893. doesn't allow deleting a directory before the directory is empty::
  894. # Delete everything reachable from the directory named in "top",
  895. # assuming there are no symbolic links.
  896. # CAUTION: This is dangerous! For example, if top == '/', it
  897. # could delete all your disk files.
  898. import os
  899. for root, dirs, files in os.walk(top, topdown=False):
  900. for name in files:
  901. os.remove(os.path.join(root, name))
  902. for name in dirs:
  903. os.rmdir(os.path.join(root, name))
  904. .. versionadded:: 2.3
  905. .. _os-process:
  906. Process Management
  907. ------------------
  908. These functions may be used to create and manage processes.
  909. The various :func:`exec\*` functions take a list of arguments for the new
  910. program loaded into the process. In each case, the first of these arguments is
  911. passed to the new program as its own name rather than as an argument a user may
  912. have typed on a command line. For the C programmer, this is the ``argv[0]``
  913. passed to a program's :cfunc:`main`. For example, ``os.execv('/bin/echo',
  914. ['foo', 'bar'])`` will only print ``bar`` on standard output; ``foo`` will seem
  915. to be ignored.
  916. .. function:: abort()
  917. Generate a :const:`SIGABRT` signal to the current process. On Unix, the default
  918. behavior is to produce a core dump; on Windows, the process immediately returns
  919. an exit code of ``3``. Be aware that programs which use :func:`signal.signal`
  920. to register a handler for :const:`SIGABRT` will behave differently.
  921. Availability: Unix, Windows.
  922. .. function:: execl(path, arg0, arg1, ...)
  923. execle(path, arg0, arg1, ..., env)
  924. execlp(file, arg0, arg1, ...)
  925. execlpe(file, arg0, arg1, ..., env)
  926. execv(path, args)
  927. execve(path, args, env)
  928. execvp(file, args)
  929. execvpe(file, args, env)
  930. These functions all execute a new program, replacing the current process; they
  931. do not return. On Unix, the new executable is loaded into the current process,
  932. and will have the same process id as the caller. Errors will be reported as
  933. :exc:`OSError` exceptions.
  934. The current process is replaced immediately. Open file objects and
  935. descriptors are not flushed, so if there may be data buffered
  936. on these open files, you should flush them using
  937. :func:`sys.stdout.flush` or :func:`os.fsync` before calling an
  938. :func:`exec\*` function.
  939. The "l" and "v" variants of the :func:`exec\*` functions differ in how
  940. command-line arguments are passed. The "l" variants are perhaps the easiest
  941. to work with if the number of parameters is fixed when the code is written; the
  942. individual parameters simply become additional parameters to the :func:`execl\*`
  943. functions. The "v" variants are good when the number of parameters is
  944. variable, with the arguments being passed in a list or tuple as the *args*
  945. parameter. In either case, the arguments to the child process should start with
  946. the name of the command being run, but this is not enforced.
  947. The variants which include a "p" near the end (:func:`execlp`,
  948. :func:`execlpe`, :func:`execvp`, and :func:`execvpe`) will use the
  949. :envvar:`PATH` environment variable to locate the program *file*. When the
  950. environment is being replaced (using one of the :func:`exec\*e` variants,
  951. discussed in the next paragraph), the new environment is used as the source of
  952. the :envvar:`PATH` variable. The other variants, :func:`execl`, :func:`execle`,
  953. :func:`execv`, and :func:`execve`, will not use the :envvar:`PATH` variable to
  954. locate the executable; *path* must contain an appropriate absolute or relative
  955. path.
  956. For :func:`execle`, :func:`execlpe`, :func:`execve`, and :func:`execvpe` (note
  957. that these all end in "e"), the *env* parameter must be a mapping which is
  958. used to define the environment variables for the new process (these are used
  959. instead of the current process' environment); the functions :func:`execl`,
  960. :func:`execlp`, :func:`execv`, and :func:`execvp` all cause the new process to
  961. inherit the environment of the current process.
  962. Availability: Unix, Windows.
  963. .. function:: _exit(n)
  964. Exit to the system with status *n*, without calling cleanup handlers, flushing
  965. stdio buffers, etc. Availability: Unix, Windows.
  966. .. note::
  967. The standard way to exit is ``sys.exit(n)``. :func:`_exit` should normally only
  968. be used in the child process after a :func:`fork`.
  969. The following exit codes are defined and can be used with :func:`_exit`,
  970. although they are not required. These are typically used for system programs
  971. written in Python, such as a mail server's external command delivery program.
  972. .. note::
  973. Some of these may not be available on all Unix platforms, since there is some
  974. variation. These constants are defined where they are defined by the underlying
  975. platform.
  976. .. data:: EX_OK
  977. Exit code that means no error occurred. Availability: Unix.
  978. .. versionadded:: 2.3
  979. .. data:: EX_USAGE
  980. Exit code that means the command was used incorrectly, such as when the wrong
  981. number of arguments are given. Availability: Unix.
  982. .. versionadded:: 2.3
  983. .. data:: EX_DATAERR
  984. Exit code that means the input data was incorrect. Availability: Unix.
  985. .. versionadded:: 2.3
  986. .. data:: EX_NOINPUT
  987. Exit code that means an input file did not exist or was not readable.
  988. Availability: Unix.
  989. .. versionadded:: 2.3
  990. .. data:: EX_NOUSER
  991. Exit code that means a specified user did not exist. Availability: Unix.
  992. .. versionadded:: 2.3
  993. .. data:: EX_NOHOST
  994. Exit code that means a specified host did not exist. Availability: Unix.
  995. .. versionadded:: 2.3
  996. .. data:: EX_UNAVAILABLE
  997. Exit code that means that a required service is unavailable. Availability:
  998. Unix.
  999. .. versionadded:: 2.3
  1000. .. data:: EX_SOFTWARE
  1001. Exit code that means an internal software error was detected. Availability:
  1002. Unix.
  1003. .. versionadded:: 2.3
  1004. .. data:: EX_OSERR
  1005. Exit code that means an operating system error was detected, such as the
  1006. inability to fork or create a pipe. Availability: Unix.
  1007. .. versionadded:: 2.3
  1008. .. data:: EX_OSFILE
  1009. Exit code that means some system file did not exist, could not be opened, or had
  1010. some other kind of error. Availability: Unix.
  1011. .. versionadded:: 2.3
  1012. .. data:: EX_CANTCREAT
  1013. Exit code that means a user specified output file could not be created.
  1014. Availability: Unix.
  1015. .. versionadded:: 2.3
  1016. .. data:: EX_IOERR
  1017. Exit code that means that an error occurred while doing I/O on some file.
  1018. Availability: Unix.
  1019. .. versionadded:: 2.3
  1020. .. data:: EX_TEMPFAIL
  1021. Exit code that means a temporary failure occurred. This indicates something
  1022. that may not really be an error, such as a network connection that couldn't be
  1023. made during a retryable operation. Availability: Unix.
  1024. .. versionadded:: 2.3
  1025. .. data:: EX_PROTOCOL
  1026. Exit code that means that a protocol exchange was illegal, invalid, or not
  1027. understood. Availability: Unix.
  1028. .. versionadded:: 2.3
  1029. .. data:: EX_NOPERM
  1030. Exit code that means that there were insufficient permissions to perform the
  1031. operation (but not intended for file system problems). Availability: Unix.
  1032. .. versionadded:: 2.3
  1033. .. data:: EX_CONFIG
  1034. Exit code that means that some kind of configuration error occurred.
  1035. Availability: Unix.
  1036. .. versionadded:: 2.3
  1037. .. data:: EX_NOTFOUND
  1038. Exit code that means something like "an entry was not found". Availability:
  1039. Unix.
  1040. .. versionadded:: 2.3
  1041. .. function:: fork()
  1042. Fork a child process. Return ``0`` in the child and the child's process id in the
  1043. parent. If an error occurs :exc:`OSError` is raised.
  1044. Note that some platforms including FreeBSD <= 6.3, Cygwin and OS/2 EMX have
  1045. known issues when using fork() from a thread.
  1046. Availability: Unix.
  1047. .. function:: forkpty()
  1048. Fork a child process, using a new pseudo-terminal as the child's controlling
  1049. terminal. Return a pair of ``(pid, fd)``, where *pid* is ``0`` in the child, the
  1050. new child's process id in the parent, and *fd* is the file descriptor of the
  1051. master end of the pseudo-terminal. For a more portable approach, use the
  1052. :mod:`pty` module. If an error occurs :exc:`OSError` is raised.
  1053. Availability: some flavors of Unix.
  1054. .. function:: kill(pid, sig)
  1055. .. index::
  1056. single: process; killing
  1057. single: process; signalling
  1058. Send signal *sig* to the process *pid*. Constants for the specific signals
  1059. available on the host platform are defined in the :mod:`signal` module.
  1060. Availability: Unix.
  1061. .. function:: killpg(pgid, sig)
  1062. .. index::
  1063. single: process; killing
  1064. single: process; signalling
  1065. Send the signal *sig* to the process group *pgid*. Availability: Unix.
  1066. .. versionadded:: 2.3
  1067. .. function:: nice(increment)
  1068. Add *increment* to the process's "niceness". Return the new niceness.
  1069. Availability: Unix.
  1070. .. function:: plock(op)
  1071. Lock program segments into memory. The value of *op* (defined in
  1072. ``<sys/lock.h>``) determines which segments are locked. Availability: Unix.
  1073. .. function:: popen(...)
  1074. popen2(...)
  1075. popen3(...)
  1076. popen4(...)
  1077. :noindex:
  1078. Run child processes, returning opened pipes for communications. These functions
  1079. are described in section :ref:`os-newstreams`.
  1080. .. function:: spawnl(mode, path, ...)
  1081. spawnle(mode, path, ..., env)
  1082. spawnlp(mode, file, ...)
  1083. spawnlpe(mode, file, ..., env)
  1084. spawnv(mode, path, args)
  1085. spawnve(mode, path, args, env)
  1086. spawnvp(mode, file, args)
  1087. spawnvpe(mode, file, args, env)
  1088. Execute the program *path* in a new process.
  1089. (Note that the :mod:`subprocess` module provides more powerful facilities for
  1090. spawning new processes and retrieving their results; using that module is
  1091. preferable to using these functions. Check especially the
  1092. :ref:`subprocess-replacements` section.)
  1093. If *mode* is :const:`P_NOWAIT`, this function returns the process id of the new
  1094. process; if *mode* is :const:`P_WAIT`, returns the process's exit code if it
  1095. exits normally, or ``-signal``, where *signal* is the signal that killed the
  1096. process. On Windows, the process id will actually be the process handle, so can
  1097. be used with the :func:`waitpid` function.
  1098. The "l" and "v" variants of the :func:`spawn\*` functions differ in how
  1099. command-line arguments are passed. The "l" variants are perhaps the easiest
  1100. to work with if the number of parameters is fixed when the code is written; the
  1101. individual parameters simply become additional parameters to the
  1102. :func:`spawnl\*` functions. The "v" variants are good when the number of
  1103. parameters is variable, with the arguments being passed in a list or tuple as
  1104. the *args* parameter. In either case, the arguments to the child process must
  1105. start with the name of the command being run.
  1106. The variants which include a second "p" near the end (:func:`spawnlp`,
  1107. :func:`spawnlpe`, :func:`spawnvp`, and :func:`spawnvpe`) will use the
  1108. :envvar:`PATH` environment variable to locate the program *file*. When the
  1109. environment is being replaced (using one of the :func:`spawn\*e` variants,
  1110. discussed in the next paragraph), the new environment is used as the source of
  1111. the :envvar:`PATH` variable. The other variants, :func:`spawnl`,
  1112. :func:`spawnle`, :func:`spawnv`, and :func:`spawnve`, will not use the
  1113. :envvar:`PATH` variable to locate the executable; *path* must contain an
  1114. appropriate absolute or relative path.
  1115. For :func:`spawnle`, :func:`spawnlpe`, :func:`spawnve`, and :func:`spawnvpe`
  1116. (note that these all end in "e"), the *env* parameter must be a mapping
  1117. which is used to define the environment variables for the new process (they are
  1118. used instead of the current process' environment); the functions
  1119. :func:`spawnl`, :func:`spawnlp`, :func:`spawnv`, and :func:`spawnvp` all cause
  1120. the new process to inherit the environment of the current process. Note that
  1121. keys and values in the *env* dictionary must be strings; invalid keys or
  1122. values will cause the function to fail, with a return value of ``127``.
  1123. As an example, the following calls to :func:`spawnlp` and :func:`spawnvpe` are
  1124. equivalent::
  1125. import os
  1126. os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
  1127. L = ['cp', 'index.html', '/dev/null']
  1128. os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
  1129. Availability: Unix, Windows. :func:`spawnlp`, :func:`spawnlpe`, :func:`spawnvp`
  1130. and :func:`spawnvpe` are not available on Windows.
  1131. .. versionadded:: 1.6
  1132. .. data:: P_NOWAIT
  1133. P_NOWAITO
  1134. Possible values for the *mode* parameter to the :func:`spawn\*` family of
  1135. functions. If either of these values is given, the :func:`spawn\*` functions
  1136. will return as soon as the new process has been created, with the process id as
  1137. the return value. Availability: Unix, Windows.
  1138. .. versionadded:: 1.6
  1139. .. data:: P_WAIT
  1140. Possible value for the *mode* parameter to the :func:`spawn\*` family of
  1141. functions. If this is given as *mode*, the :func:`spawn\*` functions will not
  1142. return until the new process has run to completion and will return the exit code
  1143. of the process the run is successful, or ``-signal`` if a signal kills the
  1144. process. Availability: Unix, Windows.
  1145. .. versionadded:: 1.6
  1146. .. data:: P_DETACH
  1147. P_OVERLAY
  1148. Possible values for the *mode* parameter to the :func:`spawn\*` family of
  1149. functions. These are less portable than those listed above. :const:`P_DETACH`
  1150. is similar to :const:`P_NOWAIT`, but the new process is detached from the
  1151. console of the calling process. If :const:`P_OVERLAY` is used, the current
  1152. process will be replaced; the :func:`spawn\*` function will not return.
  1153. Availability: Windows.
  1154. .. versionadded:: 1.6
  1155. .. function:: startfile(path[, operation])
  1156. Start a file with its associated application.
  1157. When *operation* is not specified or ``'open'``, this acts like double-clicking
  1158. the file in Windows Explorer, or giving the file name as an argument to the
  1159. :program:`start` command from the interactive command shell: the file is opened
  1160. with whatever application (if any) its extension is associated.
  1161. When another *operation* is given, it must be a "command verb" that specifies
  1162. what should be done with the file. Common verbs documented by Microsoft are
  1163. ``'print'`` and ``'edit'`` (to be used on files) as well as ``'explore'`` and
  1164. ``'find'`` (to be used on directories).
  1165. :func:`startfile` returns as soon as the associated application is launched.
  1166. There is no option to wait for the application to close, and no way to retrieve
  1167. the application's exit status. The *path* parameter is relative to the current
  1168. directory. If you want to use an absolute path, make sure the first character
  1169. is not a slash (``'/'``); the underlying Win32 :cfunc:`ShellExecute` function
  1170. doesn't work if it is. Use the :func:`os.path.normpath` function to ensure that
  1171. the path is properly encoded for Win32. Availability: Windows.
  1172. .. versionadded:: 2.0
  1173. .. versionadded:: 2.5
  1174. The *operation* parameter.
  1175. .. function:: system(command)
  1176. Execute the command (a string) in a subshell. This is implemented by calling
  1177. the Standard C function :cfunc:`system`, and has the same limitations. Changes
  1178. to :data:`os.environ`, :data:`sys.stdin`, etc. are not reflected in the
  1179. environment of the executed command.
  1180. On Unix, the return value is the exit status of the process encoded in the
  1181. format specified for :func:`wait`. Note that POSIX does not specify the meaning
  1182. of the return value of the C :cfunc:`system` function, so the return value of
  1183. the Python function is system-dependent.
  1184. On Windows, the return value is that returned by the system shell after running
  1185. *command*, given by the Windows environment variable :envvar:`COMSPEC`: on
  1186. :program:`command.com` systems (Windows 95, 98 and ME) this is always ``0``; on
  1187. :program:`cmd.exe` systems (Windows NT, 2000 and XP) this is the exit status of
  1188. the command run; on systems using a non-native shell, consult your shell
  1189. documentation.
  1190. Availability: Unix, Windows.
  1191. The :mod:`subprocess` module provides more powerful facilities for spawning new
  1192. processes and retrieving their results; using that module is preferable to using
  1193. this function. Use the :mod:`subprocess` module. Check especially the
  1194. :ref:`subprocess-replacements` section.
  1195. .. function:: times()
  1196. Return a 5-tuple of floating point numbers indicating accumulated (processor or
  1197. other) times, in seconds. The items are: user time, system time, children's
  1198. user time, children's system time, and elapsed real time since a fixed point in
  1199. the past, in that order. See the Unix manual page :manpage:`times(2)` or the
  1200. corresponding Windows Platform API documentation. Availability: Unix,
  1201. Windows. On Windows, only the first two items are filled, the others are zero.
  1202. .. function:: wait()
  1203. Wait for completion of a child process, and return a tuple containing its pid
  1204. and exit status indication: a 16-bit number, whose low byte is the signal number
  1205. that killed the process, and whose high byte is the exit status (if the signal
  1206. number is zero); the high bit of the low byte is set if a core file was
  1207. produced. Availability: Unix.
  1208. .. function:: waitpid(pid, options)
  1209. The details of this function differ on Unix and Windows.
  1210. On Unix: Wait for completion of a child process given by process id *pid*, and
  1211. return a tuple containing its process id and exit status indication (encoded as
  1212. for :func:`wait`). The semantics of the call are affected by the value of the
  1213. integer *options*, which should be ``0`` for normal operation.
  1214. If *pid* is greater than ``0``, :func:`waitpid` requests status information for
  1215. that specific process. If *pid* is ``0``, the request is for the status of any
  1216. child in the process group of the current process. If *pid* is ``-1``, the
  1217. request pertains to any child of the current process. If *pid* is less than
  1218. ``-1``, status is requested for any process in the process group ``-pid`` (the
  1219. absolute value of *pid*).
  1220. An :exc:`OSError` is raised with the value of errno when the syscall
  1221. returns -1.
  1222. On Windows: Wait for completion of a process given by process handle *pid*, and
  1223. return a tuple containing *pid*, and its exit status shifted left by 8 bits
  1224. (shifting makes cross-platform use of the function easier). A *pid* less than or
  1225. equal to ``0`` has no special meaning on Windows, and raises an exception. The
  1226. value of integer *options* has no effect. *pid* can refer to any process whose
  1227. id is known, not necessarily a child process. The :func:`spawn` functions called
  1228. with :const:`P_NOWAIT` return suitable process handles.
  1229. .. function:: wait3([options])
  1230. Similar to :func:`waitpid`, except no process id argument is given and a
  1231. 3-element tuple containing the child's process id, exit status indication, and
  1232. resource usage information is returned. Refer to :mod:`resource`.\
  1233. :func:`getrusage` for details on resource usage information. The option
  1234. argument is the same as that provided to :func:`waitpid` and :func:`wait4`.
  1235. Availability: Unix.
  1236. .. versionadded:: 2.5
  1237. .. function:: wait4(pid, options)
  1238. Similar to :func:`waitpid`, except a 3-element tuple, containing the child's
  1239. process id, exit status indication, and resource usage information is returned.
  1240. Refer to :mod:`resource`.\ :func:`getrusage` for details on resource usage
  1241. information. The arguments to :func:`wait4` are the same as those provided to
  1242. :func:`waitpid`. Availability: Unix.
  1243. .. versionadded:: 2.5
  1244. .. data:: WNOHANG
  1245. The option for :func:`waitpid` to return immediately if no child process status
  1246. is available immediately. The function returns ``(0, 0)`` in this case.
  1247. Availability: Unix.
  1248. .. data:: WCONTINUED
  1249. This option causes child processes to be reported if they have been continued
  1250. from a job control stop since their status was last reported. Availability: Some
  1251. Unix systems.
  1252. .. versionadded:: 2.3
  1253. .. data:: WUNTRACED
  1254. This option causes child processes to be reported if they have been stopped but
  1255. their current state has not been reported since they were stopped. Availability:
  1256. Unix.
  1257. .. versionadded:: 2.3
  1258. The following functions take a process status code as returned by
  1259. :func:`system`, :func:`wait`, or :func:`waitpid` as a parameter. They may be
  1260. used to determine the disposition of a process.
  1261. .. function:: WCOREDUMP(status)
  1262. Return ``True`` if a core dump was generated for the process, otherwise
  1263. return ``False``. Availability: Unix.
  1264. .. versionadded:: 2.3
  1265. .. function:: WIFCONTINUED(status)
  1266. Return ``True`` if the process has been continued from a job control stop,
  1267. otherwise return ``False``. Availability: Unix.
  1268. .. versionadded:: 2.3
  1269. .. function:: WIFSTOPPED(status)
  1270. Return ``True`` if the process has been stopped, otherwise return
  1271. ``False``. Availability: Unix.
  1272. .. function:: WIFSIGNALED(status)
  1273. Return ``True`` if the process exited due to a signal, otherwise return
  1274. ``False``. Availability: Unix.
  1275. .. function:: WIFEXITED(status)
  1276. Return ``True`` if the process exited using the :manpage:`exit(2)` system call,
  1277. otherwise return ``False``. Availability: Unix.
  1278. .. function:: WEXITSTATUS(status)
  1279. If ``WIFEXITED(status)`` is true, return the integer parameter to the
  1280. :manpage:`exit(2)` system call. Otherwise, the return value is meaningless.
  1281. Availability: Unix.
  1282. .. function:: WSTOPSIG(status)
  1283. Return the signal which caused the process to stop. Availability: Unix.
  1284. .. function:: WTERMSIG(status)
  1285. Return the signal which caused the process to exit. Availability: Unix.
  1286. .. _os-path:
  1287. Miscellaneous System Information
  1288. --------------------------------
  1289. .. function:: confstr(name)
  1290. Return string-valued system configuration values. *name* specifies the
  1291. configuration value to retrieve; it may be a string which is the name of a
  1292. defined system value; these names are specified in a number of standards (POSIX,
  1293. Unix 95, Unix 98, and others). Some platforms define additional names as well.
  1294. The names known to the host operating system are given as the keys of the
  1295. ``confstr_names`` dictionary. For configuration variables not included in that
  1296. mapping, passing an integer for *name* is also accepted. Availability:
  1297. Unix.
  1298. If the configuration value specified by *name* isn't defined, ``None`` is
  1299. returned.
  1300. If *name* is a string and is not known, :exc:`ValueError` is raised. If a
  1301. specific value for *name* is not supported by the host system, even if it is
  1302. included in ``confstr_names``, an :exc:`OSError` is raised with
  1303. :const:`errno.EINVAL` for the error number.
  1304. .. data:: confstr_names
  1305. Dictionary mapping names accepted by :func:`confstr` to the integer values
  1306. defined for those names by the host operating system. This can be used to
  1307. determine the set of names known to the system. Availability: Unix.
  1308. .. function:: getloadavg()
  1309. Return the number of processes in the system run queue averaged over the last
  1310. 1, 5, and 15 minutes or raises :exc:`OSError` if the load average was
  1311. unobtainable. Availability: Unix.
  1312. .. versionadded:: 2.3
  1313. .. function:: sysconf(name)
  1314. Return integer-valued system configuration values. If the configuration value
  1315. specified by *name* isn't defined, ``-1`` is returned. The comments regarding
  1316. the *name* parameter for :func:`confstr` apply here as well; the dictionary that
  1317. provides information on the known names is given by ``sysconf_names``.
  1318. Availability: Unix.
  1319. .. data:: sysconf_names
  1320. Dictionary mapping names accepted by :func:`sysconf` to the integer values
  1321. defined for those names by the host operating system. This can be used to
  1322. determine the set of names known to the system. Availability: Unix.
  1323. The following data values are used to support path manipulation operations. These
  1324. are defined for all platforms.
  1325. Higher-level operations on pathnames are defined in the :mod:`os.path` module.
  1326. .. data:: curdir
  1327. The constant string used by the operating system to refer to the current
  1328. directory. This is ``'.'`` for Windows and POSIX. Also available via
  1329. :mod:`os.path`.
  1330. .. data:: pardir
  1331. The constant string used by the operating system to refer to the parent
  1332. directory. This is ``'..'`` for Windows and POSIX. Also available via
  1333. :mod:`os.path`.
  1334. .. data:: sep
  1335. The character used by the operating system to separate pathname components.
  1336. This is ``'/'`` for POSIX and ``'\\'`` for Windows. Note that knowing this
  1337. is not sufficient to be able to parse or concatenate pathnames --- use
  1338. :func:`os.path.split` and :func:`os.path.join` --- but it is occasionally
  1339. useful. Also available via :mod:`os.path`.
  1340. .. data:: altsep
  1341. An alternative character used by the operating system to separate pathname
  1342. components, or ``None`` if only one separator character exists. This is set to
  1343. ``'/'`` on Windows systems where ``sep`` is a backslash. Also available via
  1344. :mod:`os.path`.
  1345. .. data:: extsep
  1346. The character which separates the base filename from the extension; for example,
  1347. the ``'.'`` in :file:`os.py`. Also available via :mod:`os.path`.
  1348. .. versionadded:: 2.2
  1349. .. data:: pathsep
  1350. The character conventionally used by the operating system to separate search
  1351. path components (as in :envvar:`PATH`), such as ``':'`` for POSIX or ``';'`` for
  1352. Windows. Also available via :mod:`os.path`.
  1353. .. data:: defpath
  1354. The default search path used by :func:`exec\*p\*` and :func:`spawn\*p\*` if the
  1355. environment doesn't have a ``'PATH'`` key. Also available via :mod:`os.path`.
  1356. .. data:: linesep
  1357. The string used to separate (or, rather, terminate) lines on the current
  1358. platform. This may be a single character, such as ``'\n'`` for POSIX, or
  1359. multiple characters, for example, ``'\r\n'`` for Windows. Do not use
  1360. *os.linesep* as a line terminator when writing files opened in text mode (the
  1361. default); use a single ``'\n'`` instead, on all platforms.
  1362. .. data:: devnull
  1363. The file path of the null device. For example: ``'/dev/null'`` for POSIX.
  1364. Also available via :mod:`os.path`.
  1365. .. versionadded:: 2.4
  1366. .. _os-miscfunc:
  1367. Miscellaneous Functions
  1368. -----------------------
  1369. .. function:: urandom(n)
  1370. Return a string of *n* random bytes suitable for cryptographic use.
  1371. This function returns random bytes from an OS-specific randomness source. The
  1372. returned data should be unpredictable enough for cryptographic applications,
  1373. though its exact quality depends on the OS implementation. On a UNIX-like
  1374. system this will query /dev/urandom, and on Windows it will use CryptGenRandom.
  1375. If a randomness source is not found, :exc:`NotImplementedError` will be raised.
  1376. .. versionadded:: 2.4