1 \section{\module{os
} ---
2 Miscellaneous operating system interfaces
}
4 \declaremodule{standard
}{os
}
5 \modulesynopsis{Miscellaneous operating system interfaces.
}
8 This module provides a more portable way of using operating system
9 dependent functionality than importing a operating system dependent
10 built-in module like
\refmodule{posix
} or
\module{nt
}.
12 This module searches for an operating system dependent built-in module like
13 \module{mac
} or
\refmodule{posix
} and exports the same functions and data
14 as found there. The design of all Python's built-in operating system dependent
15 modules is such that as long as the same functionality is available,
16 it uses the same interface; for example, the function
17 \code{os.stat(
\var{path
})
} returns stat information about
\var{path
} in
18 the same format (which happens to have originated with the
21 Extensions peculiar to a particular operating system are also
22 available through the
\module{os
} module, but using them is of course a
23 threat to portability!
25 Note that after the first time
\module{os
} is imported, there is
26 \emph{no
} performance penalty in using functions from
\module{os
}
27 instead of directly from the operating system dependent built-in module,
28 so there should be
\emph{no
} reason not to use
\module{os
}!
31 % Frank Stajano <fstajano@uk.research.att.com> complained that it
32 % wasn't clear that the entries described in the subsections were all
33 % available at the module level (most uses of subsections are
34 % different); I think this is only a problem for the HTML version,
35 % where the relationship may not be as clear.
38 The
\module{os
} module contains many functions and data values.
39 The items below and in the following sub-sections are all available
40 directly from the
\module{os
} module.
44 \begin{excdesc
}{error
}
45 This exception is raised when a function returns a system-related
46 error (not for illegal argument types or other incidental errors).
47 This is also known as the built-in exception
\exception{OSError
}. The
48 accompanying value is a pair containing the numeric error code from
49 \cdata{errno
} and the corresponding string, as would be printed by the
50 C function
\cfunction{perror()
}. See the module
51 \refmodule{errno
}\refbimodindex{errno
}, which contains names for the
52 error codes defined by the underlying operating system.
54 When exceptions are classes, this exception carries two attributes,
55 \member{errno
} and
\member{strerror
}. The first holds the value of
56 the C
\cdata{errno
} variable, and the latter holds the corresponding
57 error message from
\cfunction{strerror()
}. For exceptions that
58 involve a file system path (such as
\function{chdir()
} or
59 \function{unlink()
}), the exception instance will contain a third
60 attribute,
\member{filename
}, which is the file name passed to the
64 \begin{datadesc
}{name
}
65 The name of the operating system dependent module imported. The
66 following names have currently been registered:
\code{'posix'
},
67 \code{'nt'
},
\code{'mac'
},
\code{'os2'
},
\code{'ce'
},
68 \code{'java'
},
\code{'riscos'
}.
71 \begin{datadesc
}{path
}
72 The corresponding operating system dependent standard module for pathname
73 operations, such as
\module{posixpath
} or
\module{macpath
}. Thus,
74 given the proper imports,
\code{os.path.split(
\var{file
})
} is
75 equivalent to but more portable than
76 \code{posixpath.split(
\var{file
})
}. Note that this is also an
77 importable module: it may be imported directly as
83 \subsection{Process Parameters
\label{os-procinfo
}}
85 These functions and data items provide information and operate on the
86 current process and user.
88 \begin{datadesc
}{environ
}
89 A mapping object representing the string environment. For example,
90 \code{environ
['HOME'
]} is the pathname of your home directory (on some
91 platforms), and is equivalent to
\code{getenv("HOME")
} in C.
93 If the platform supports the
\function{putenv()
} function, this
94 mapping may be used to modify the environment as well as query the
95 environment.
\function{putenv()
} will be called automatically when
96 the mapping is modified.
\note{On some platforms, including
97 FreeBSD and Mac OS X, setting
\code{environ
} may cause memory leaks.
98 Refer to the system documentation for putenv.
}
100 If
\function{putenv()
} is not provided, this mapping may be passed to
101 the appropriate process-creation functions to cause child processes to
102 use a modified environment.
105 \begin{funcdescni
}{chdir
}{path
}
106 \funclineni{fchdir
}{fd
}
107 \funclineni{getcwd
}{}
108 These functions are described in ``Files and Directories'' (section
112 \begin{funcdesc
}{ctermid
}{}
113 Return the filename corresponding to the controlling terminal of the
118 \begin{funcdesc
}{getegid
}{}
119 Return the effective group id of the current process. This
120 corresponds to the `set id' bit on the file being executed in the
125 \begin{funcdesc
}{geteuid
}{}
126 \index{user!effective id
}
127 Return the current process' effective user id.
131 \begin{funcdesc
}{getgid
}{}
132 \index{process!group
}
133 Return the real group id of the current process.
137 \begin{funcdesc
}{getgroups
}{}
138 Return list of supplemental group ids associated with the current
143 \begin{funcdesc
}{getlogin
}{}
144 Return the name of the user logged in on the controlling terminal of
145 the process. For most purposes, it is more useful to use the
146 environment variable
\envvar{LOGNAME
} to find out who the user is,
147 or
\code{pwd.getpwuid(os.getuid())
[0]} to get the login name
148 of the currently effective user ID.
152 \begin{funcdesc
}{getpgid
}{pid
}
153 Return the process group id of the process with process id
\var{pid
}.
154 If
\var{pid
} is
0, the process group id of the current process is
155 returned. Availability:
\UNIX.
159 \begin{funcdesc
}{getpgrp
}{}
160 \index{process!group
}
161 Return the id of the current process group.
165 \begin{funcdesc
}{getpid
}{}
167 Return the current process id.
168 Availability:
\UNIX, Windows.
171 \begin{funcdesc
}{getppid
}{}
172 \index{process!id of parent
}
173 Return the parent's process id.
177 \begin{funcdesc
}{getuid
}{}
179 Return the current process' user id.
183 \begin{funcdesc
}{getenv
}{varname
\optional{, value
}}
184 Return the value of the environment variable
\var{varname
} if it
185 exists, or
\var{value
} if it doesn't.
\var{value
} defaults to
187 Availability: most flavors of
\UNIX, Windows.
190 \begin{funcdesc
}{putenv
}{varname, value
}
191 \index{environment variables!setting
}
192 Set the environment variable named
\var{varname
} to the string
193 \var{value
}. Such changes to the environment affect subprocesses
194 started with
\function{os.system()
},
\function{popen()
} or
195 \function{fork()
} and
\function{execv()
}.
196 Availability: most flavors of
\UNIX, Windows.
198 \note{On some platforms, including FreeBSD and Mac OS X,
199 setting
\code{environ
} may cause memory leaks.
200 Refer to the system documentation for putenv.
}
202 When
\function{putenv()
} is
203 supported, assignments to items in
\code{os.environ
} are automatically
204 translated into corresponding calls to
\function{putenv()
}; however,
205 calls to
\function{putenv()
} don't update
\code{os.environ
}, so it is
206 actually preferable to assign to items of
\code{os.environ
}.
209 \begin{funcdesc
}{setegid
}{egid
}
210 Set the current process's effective group id.
214 \begin{funcdesc
}{seteuid
}{euid
}
215 Set the current process's effective user id.
219 \begin{funcdesc
}{setgid
}{gid
}
220 Set the current process' group id.
224 \begin{funcdesc
}{setgroups
}{groups
}
225 Set the list of supplemental group ids associated with the current
226 process to
\var{groups
}.
\var{groups
} must be a sequence, and each
227 element must be an integer identifying a group. This operation is
228 typical available only to the superuser.
233 \begin{funcdesc
}{setpgrp
}{}
234 Calls the system call
\cfunction{setpgrp()
} or
\cfunction{setpgrp(
0,
235 0)
} depending on which version is implemented (if any). See the
236 \UNIX{} manual for the semantics.
240 \begin{funcdesc
}{setpgid
}{pid, pgrp
} Calls the system call
241 \cfunction{setpgid()
} to set the process group id of the process with
242 id
\var{pid
} to the process group with id
\var{pgrp
}. See the
\UNIX{}
243 manual for the semantics.
247 \begin{funcdesc
}{setreuid
}{ruid, euid
}
248 Set the current process's real and effective user ids.
252 \begin{funcdesc
}{setregid
}{rgid, egid
}
253 Set the current process's real and effective group ids.
257 \begin{funcdesc
}{getsid
}{pid
}
258 Calls the system call
\cfunction{getsid()
}. See the
\UNIX{} manual
260 Availability:
\UNIX.
\versionadded{2.4}
263 \begin{funcdesc
}{setsid
}{}
264 Calls the system call
\cfunction{setsid()
}. See the
\UNIX{} manual
269 \begin{funcdesc
}{setuid
}{uid
}
270 \index{user!id, setting
}
271 Set the current process' user id.
275 % placed in this section since it relates to errno.... a little weak
276 \begin{funcdesc
}{strerror
}{code
}
277 Return the error message corresponding to the error code in
279 Availability:
\UNIX, Windows.
282 \begin{funcdesc
}{umask
}{mask
}
283 Set the current numeric umask and returns the previous umask.
284 Availability:
\UNIX, Windows.
287 \begin{funcdesc
}{uname
}{}
288 Return a
5-tuple containing information identifying the current
289 operating system. The tuple contains
5 strings:
290 \code{(
\var{sysname
},
\var{nodename
},
\var{release
},
\var{version
},
291 \var{machine
})
}. Some systems truncate the nodename to
8
292 characters or to the leading component; a better way to get the
293 hostname is
\function{socket.gethostname()
}
294 \withsubitem{(in module socket)
}{\ttindex{gethostname()
}}
296 \withsubitem{(in module socket)
}{\ttindex{gethostbyaddr()
}}
297 \code{socket.gethostbyaddr(socket.gethostname())
}.
298 Availability: recent flavors of
\UNIX.
303 \subsection{File Object Creation
\label{os-newstreams
}}
305 These functions create new file objects.
308 \begin{funcdesc
}{fdopen
}{fd
\optional{, mode
\optional{, bufsize
}}}
309 Return an open file object connected to the file descriptor
\var{fd
}.
310 \index{I/O control!buffering
}
311 The
\var{mode
} and
\var{bufsize
} arguments have the same meaning as
312 the corresponding arguments to the built-in
\function{open()
}
314 Availability: Macintosh,
\UNIX, Windows.
316 \versionchanged[When specified, the
\var{mode
} argument must now start
317 with one of the letters
\character{r
},
\character{w
}, or
\character{a
},
318 otherwise a
\exception{ValueError
} is raised
]{2.3}
321 \begin{funcdesc
}{popen
}{command
\optional{, mode
\optional{, bufsize
}}}
322 Open a pipe to or from
\var{command
}. The return value is an open
323 file object connected to the pipe, which can be read or written
324 depending on whether
\var{mode
} is
\code{'r'
} (default) or
\code{'w'
}.
325 The
\var{bufsize
} argument has the same meaning as the corresponding
326 argument to the built-in
\function{open()
} function. The exit status of
327 the command (encoded in the format specified for
\function{wait()
}) is
328 available as the return value of the
\method{close()
} method of the file
329 object, except that when the exit status is zero (termination without
330 errors),
\code{None
} is returned.
331 Availability:
\UNIX, Windows.
333 \versionchanged[This function worked unreliably under Windows in
334 earlier versions of Python. This was due to the use of the
335 \cfunction{_popen()
} function from the libraries provided with
336 Windows. Newer versions of Python do not use the broken
337 implementation from the Windows libraries
]{2.0}
340 \begin{funcdesc
}{tmpfile
}{}
341 Return a new file object opened in update mode (
\samp{w+b
}). The file
342 has no directory entries associated with it and will be automatically
343 deleted once there are no file descriptors for the file.
344 Availability:
\UNIX, Windows.
348 For each of these
\function{popen()
} variants, if
\var{bufsize
} is
349 specified, it specifies the buffer size for the I/O pipes.
350 \var{mode
}, if provided, should be the string
\code{'b'
} or
351 \code{'t'
}; on Windows this is needed to determine whether the file
352 objects should be opened in binary or text mode. The default value
353 for
\var{mode
} is
\code{'t'
}.
355 These methods do not make it possible to retrieve the return code from
356 the child processes. The only way to control the input and output
357 streams and also retrieve the return codes is to use the
358 \class{Popen3
} and
\class{Popen4
} classes from the
\refmodule{popen2
}
359 module; these are only available on
\UNIX.
361 For a discussion of possible deadlock conditions related to the use
362 of these functions, see ``
\ulink{Flow Control
363 Issues
}{popen2-flow-control.html
}''
364 (section~
\ref{popen2-flow-control
}).
366 \begin{funcdesc
}{popen2
}{cmd
\optional{, mode
\optional{, bufsize
}}}
367 Executes
\var{cmd
} as a sub-process. Returns the file objects
368 \code{(
\var{child_stdin
},
\var{child_stdout
})
}.
369 Availability:
\UNIX, Windows.
373 \begin{funcdesc
}{popen3
}{cmd
\optional{, mode
\optional{, bufsize
}}}
374 Executes
\var{cmd
} as a sub-process. Returns the file objects
375 \code{(
\var{child_stdin
},
\var{child_stdout
},
\var{child_stderr
})
}.
376 Availability:
\UNIX, Windows.
380 \begin{funcdesc
}{popen4
}{cmd
\optional{, mode
\optional{, bufsize
}}}
381 Executes
\var{cmd
} as a sub-process. Returns the file objects
382 \code{(
\var{child_stdin
},
\var{child_stdout_and_stderr
})
}.
384 (Note that
\code{\var{child_stdin
},
\var{child_stdout
}, and
385 \var{child_stderr
}} are named from the point of view of the child
386 process, i.e.
\var{child_stdin
} is the child's standard input.)
388 Availability:
\UNIX, Windows.
392 This functionality is also available in the
\refmodule{popen2
} module
393 using functions of the same names, but the return values of those
394 functions have a different order.
397 \subsection{File Descriptor Operations
\label{os-fd-ops
}}
399 These functions operate on I/O streams referred to
400 using file descriptors.
403 \begin{funcdesc
}{close
}{fd
}
404 Close file descriptor
\var{fd
}.
405 Availability: Macintosh,
\UNIX, Windows.
408 This function is intended for low-level I/O and must be applied
409 to a file descriptor as returned by
\function{open()
} or
410 \function{pipe()
}. To close a ``file object'' returned by the
411 built-in function
\function{open()
} or by
\function{popen()
} or
412 \function{fdopen()
}, use its
\method{close()
} method.
416 \begin{funcdesc
}{dup
}{fd
}
417 Return a duplicate of file descriptor
\var{fd
}.
418 Availability: Macintosh,
\UNIX, Windows.
421 \begin{funcdesc
}{dup2
}{fd, fd2
}
422 Duplicate file descriptor
\var{fd
} to
\var{fd2
}, closing the latter
424 Availability:
\UNIX, Windows.
427 \begin{funcdesc
}{fdatasync
}{fd
}
428 Force write of file with filedescriptor
\var{fd
} to disk.
429 Does not force update of metadata.
433 \begin{funcdesc
}{fpathconf
}{fd, name
}
434 Return system configuration information relevant to an open file.
435 \var{name
} specifies the configuration value to retrieve; it may be a
436 string which is the name of a defined system value; these names are
437 specified in a number of standards (
\POSIX.1,
\UNIX{} 95,
\UNIX{} 98, and
438 others). Some platforms define additional names as well. The names
439 known to the host operating system are given in the
440 \code{pathconf_names
} dictionary. For configuration variables not
441 included in that mapping, passing an integer for
\var{name
} is also
445 If
\var{name
} is a string and is not known,
\exception{ValueError
} is
446 raised. If a specific value for
\var{name
} is not supported by the
447 host system, even if it is included in
\code{pathconf_names
}, an
448 \exception{OSError
} is raised with
\constant{errno.EINVAL
} for the
452 \begin{funcdesc
}{fstat
}{fd
}
453 Return status for file descriptor
\var{fd
}, like
\function{stat()
}.
454 Availability:
\UNIX, Windows.
457 \begin{funcdesc
}{fstatvfs
}{fd
}
458 Return information about the filesystem containing the file associated
459 with file descriptor
\var{fd
}, like
\function{statvfs()
}.
463 \begin{funcdesc
}{fsync
}{fd
}
464 Force write of file with filedescriptor
\var{fd
} to disk. On
\UNIX,
465 this calls the native
\cfunction{fsync()
} function; on Windows, the
466 MS
\cfunction{_commit()
} function.
468 If you're starting with a Python file object
\var{f
}, first do
469 \code{\var{f
}.flush()
}, and then do
\code{os.fsync(
\var{f
}.fileno())
},
470 to ensure that all internal buffers associated with
\var{f
} are written
472 Availability:
\UNIX, and Windows starting in
2.2.3.
475 \begin{funcdesc
}{ftruncate
}{fd, length
}
476 Truncate the file corresponding to file descriptor
\var{fd
},
477 so that it is at most
\var{length
} bytes in size.
481 \begin{funcdesc
}{isatty
}{fd
}
482 Return
\code{True
} if the file descriptor
\var{fd
} is open and
483 connected to a tty(-like) device, else
\code{False
}.
487 \begin{funcdesc
}{lseek
}{fd, pos, how
}
488 Set the current position of file descriptor
\var{fd
} to position
489 \var{pos
}, modified by
\var{how
}:
\code{0} to set the position
490 relative to the beginning of the file;
\code{1} to set it relative to
491 the current position;
\code{2} to set it relative to the end of the
493 Availability: Macintosh,
\UNIX, Windows.
496 \begin{funcdesc
}{open
}{file, flags
\optional{, mode
}}
497 Open the file
\var{file
} and set various flags according to
498 \var{flags
} and possibly its mode according to
\var{mode
}.
499 The default
\var{mode
} is
\code{0777} (octal), and the current umask
500 value is first masked out. Return the file descriptor for the newly
502 Availability: Macintosh,
\UNIX, Windows.
504 For a description of the flag and mode values, see the C run-time
505 documentation; flag constants (like
\constant{O_RDONLY
} and
506 \constant{O_WRONLY
}) are defined in this module too (see below).
509 This function is intended for low-level I/O. For normal usage,
510 use the built-in function
\function{open()
}, which returns a ``file
511 object'' with
\method{read()
} and
\method{write()
} methods (and many
516 \begin{funcdesc
}{openpty
}{}
517 Open a new pseudo-terminal pair. Return a pair of file descriptors
518 \code{(
\var{master
},
\var{slave
})
} for the pty and the tty,
519 respectively. For a (slightly) more portable approach, use the
520 \refmodule{pty
}\refstmodindex{pty
} module.
521 Availability: Some flavors of
\UNIX.
524 \begin{funcdesc
}{pipe
}{}
525 Create a pipe. Return a pair of file descriptors
\code{(
\var{r
},
526 \var{w
})
} usable for reading and writing, respectively.
527 Availability:
\UNIX, Windows.
530 \begin{funcdesc
}{read
}{fd, n
}
531 Read at most
\var{n
} bytes from file descriptor
\var{fd
}.
532 Return a string containing the bytes read. If the end of the file
533 referred to by
\var{fd
} has been reached, an empty string is
535 Availability: Macintosh,
\UNIX, Windows.
538 This function is intended for low-level I/O and must be applied
539 to a file descriptor as returned by
\function{open()
} or
540 \function{pipe()
}. To read a ``file object'' returned by the
541 built-in function
\function{open()
} or by
\function{popen()
} or
542 \function{fdopen()
}, or
\code{sys.stdin
}, use its
543 \method{read()
} or
\method{readline()
} methods.
547 \begin{funcdesc
}{tcgetpgrp
}{fd
}
548 Return the process group associated with the terminal given by
549 \var{fd
} (an open file descriptor as returned by
\function{open()
}).
553 \begin{funcdesc
}{tcsetpgrp
}{fd, pg
}
554 Set the process group associated with the terminal given by
555 \var{fd
} (an open file descriptor as returned by
\function{open()
})
560 \begin{funcdesc
}{ttyname
}{fd
}
561 Return a string which specifies the terminal device associated with
562 file-descriptor
\var{fd
}. If
\var{fd
} is not associated with a terminal
563 device, an exception is raised.
567 \begin{funcdesc
}{write
}{fd, str
}
568 Write the string
\var{str
} to file descriptor
\var{fd
}.
569 Return the number of bytes actually written.
570 Availability: Macintosh,
\UNIX, Windows.
573 This function is intended for low-level I/O and must be applied
574 to a file descriptor as returned by
\function{open()
} or
575 \function{pipe()
}. To write a ``file object'' returned by the
576 built-in function
\function{open()
} or by
\function{popen()
} or
577 \function{fdopen()
}, or
\code{sys.stdout
} or
\code{sys.stderr
}, use
578 its
\method{write()
} method.
583 The following data items are available for use in constructing the
584 \var{flags
} parameter to the
\function{open()
} function.
586 \begin{datadesc
}{O_RDONLY
}
590 \dataline{O_NONBLOCK
}
599 Options for the
\var{flag
} argument to the
\function{open()
} function.
600 These can be bit-wise OR'd together.
601 Availability: Macintosh,
\UNIX, Windows.
602 % XXX O_NDELAY, O_NONBLOCK, O_DSYNC, O_RSYNC, O_SYNC, O_NOCTTY are not on Windows.
605 \begin{datadesc
}{O_BINARY
}
606 Option for the
\var{flag
} argument to the
\function{open()
} function.
607 This can be bit-wise OR'd together with those listed above.
608 Availability: Macintosh, Windows.
609 % XXX need to check on the availability of this one.
612 \begin{datadesc
}{O_NOINHERIT
}
613 \dataline{O_SHORT_LIVED
}
614 \dataline{O_TEMPORARY
}
616 \dataline{O_SEQUENTIAL
}
618 Options for the
\var{flag
} argument to the
\function{open()
} function.
619 These can be bit-wise OR'd together.
620 Availability: Windows.
623 \subsection{Files and Directories
\label{os-file-dir
}}
625 \begin{funcdesc
}{access
}{path, mode
}
626 Use the real uid/gid to test for access to
\var{path
}. Note that most
627 operations will use the effective uid/gid, therefore this routine can
628 be used in a suid/sgid environment to test if the invoking user has the
629 specified access to
\var{path
}.
\var{mode
} should be
\constant{F_OK
}
630 to test the existence of
\var{path
}, or it can be the inclusive OR of
631 one or more of
\constant{R_OK
},
\constant{W_OK
}, and
\constant{X_OK
} to
632 test permissions. Return
\constant{True
} if access is allowed,
633 \constant{False
} if not.
634 See the
\UNIX{} man page
\manpage{access
}{2} for more information.
635 Availability:
\UNIX, Windows.
638 \begin{datadesc
}{F_OK
}
639 Value to pass as the
\var{mode
} parameter of
\function{access()
} to
640 test the existence of
\var{path
}.
643 \begin{datadesc
}{R_OK
}
644 Value to include in the
\var{mode
} parameter of
\function{access()
}
645 to test the readability of
\var{path
}.
648 \begin{datadesc
}{W_OK
}
649 Value to include in the
\var{mode
} parameter of
\function{access()
}
650 to test the writability of
\var{path
}.
653 \begin{datadesc
}{X_OK
}
654 Value to include in the
\var{mode
} parameter of
\function{access()
}
655 to determine if
\var{path
} can be executed.
658 \begin{funcdesc
}{chdir
}{path
}
659 \index{directory!changing
}
660 Change the current working directory to
\var{path
}.
661 Availability: Macintosh,
\UNIX, Windows.
664 \begin{funcdesc
}{fchdir
}{fd
}
665 Change the current working directory to the directory represented by
666 the file descriptor
\var{fd
}. The descriptor must refer to an opened
667 directory, not an open file.
672 \begin{funcdesc
}{getcwd
}{}
673 Return a string representing the current working directory.
674 Availability: Macintosh,
\UNIX, Windows.
677 \begin{funcdesc
}{getcwdu
}{}
678 Return a Unicode object representing the current working directory.
679 Availability:
\UNIX, Windows.
683 \begin{funcdesc
}{chroot
}{path
}
684 Change the root directory of the current process to
\var{path
}.
689 \begin{funcdesc
}{chmod
}{path, mode
}
690 Change the mode of
\var{path
} to the numeric
\var{mode
}.
691 \var{mode
} may take one of the following values
692 (as defined in the
\module{stat
} module):
699 \item \code{S_IWRITE
}
714 Availability:
\UNIX, Windows.
717 \begin{funcdesc
}{chown
}{path, uid, gid
}
718 Change the owner and group id of
\var{path
} to the numeric
\var{uid
}
723 \begin{funcdesc
}{lchown
}{path, uid, gid
}
724 Change the owner and group id of
\var{path
} to the numeric
\var{uid
}
725 and gid. This function will not follow symbolic links.
730 \begin{funcdesc
}{link
}{src, dst
}
731 Create a hard link pointing to
\var{src
} named
\var{dst
}.
735 \begin{funcdesc
}{listdir
}{path
}
736 Return a list containing the names of the entries in the directory.
737 The list is in arbitrary order. It does not include the special
738 entries
\code{'.'
} and
\code{'..'
} even if they are present in the
740 Availability: Macintosh,
\UNIX, Windows.
742 \versionchanged[On Windows NT/
2k/XP and Unix, if
\var{path
} is a Unicode
743 object, the result will be a list of Unicode objects.
]{2.3}
746 \begin{funcdesc
}{lstat
}{path
}
747 Like
\function{stat()
}, but do not follow symbolic links.
751 \begin{funcdesc
}{mkfifo
}{path
\optional{, mode
}}
752 Create a FIFO (a named pipe) named
\var{path
} with numeric mode
753 \var{mode
}. The default
\var{mode
} is
\code{0666} (octal). The current
754 umask value is first masked out from the mode.
757 FIFOs are pipes that can be accessed like regular files. FIFOs exist
758 until they are deleted (for example with
\function{os.unlink()
}).
759 Generally, FIFOs are used as rendezvous between ``client'' and
760 ``server'' type processes: the server opens the FIFO for reading, and
761 the client opens it for writing. Note that
\function{mkfifo()
}
762 doesn't open the FIFO --- it just creates the rendezvous point.
765 \begin{funcdesc
}{mknod
}{path
\optional{, mode=
0600, device
}}
766 Create a filesystem node (file, device special file or named pipe)
767 named filename.
\var{mode
} specifies both the permissions to use and
768 the type of node to be created, being combined (bitwise OR) with one
769 of S_IFREG, S_IFCHR, S_IFBLK, and S_IFIFO (those constants are
770 available in
\module{stat
}). For S_IFCHR and S_IFBLK,
\var{device
}
771 defines the newly created device special file (probably using
772 \function{os.makedev()
}), otherwise it is ignored.
776 \begin{funcdesc
}{major
}{device
}
777 Extracts a device major number from a raw device number.
781 \begin{funcdesc
}{minor
}{device
}
782 Extracts a device minor number from a raw device number.
786 \begin{funcdesc
}{makedev
}{major, minor
}
787 Composes a raw device number from the major and minor device numbers.
791 \begin{funcdesc
}{mkdir
}{path
\optional{, mode
}}
792 Create a directory named
\var{path
} with numeric mode
\var{mode
}.
793 The default
\var{mode
} is
\code{0777} (octal). On some systems,
794 \var{mode
} is ignored. Where it is used, the current umask value is
796 Availability: Macintosh,
\UNIX, Windows.
799 \begin{funcdesc
}{makedirs
}{path
\optional{, mode
}}
800 Recursive directory creation function.
\index{directory!creating
}
801 \index{UNC paths!and
\function{os.makedirs()
}}
802 Like
\function{mkdir()
},
803 but makes all intermediate-level directories needed to contain the
804 leaf directory. Throws an
\exception{error
} exception if the leaf
805 directory already exists or cannot be created. The default
\var{mode
}
806 is
\code{0777} (octal). This function does not properly handle UNC
807 paths (only relevant on Windows systems; Universal Naming Convention
808 paths are those that use the `
\code{\e\e host
\e path
}' syntax).
812 \begin{funcdesc
}{pathconf
}{path, name
}
813 Return system configuration information relevant to a named file.
814 \var{name
} specifies the configuration value to retrieve; it may be a
815 string which is the name of a defined system value; these names are
816 specified in a number of standards (
\POSIX.1,
\UNIX{} 95,
\UNIX{} 98, and
817 others). Some platforms define additional names as well. The names
818 known to the host operating system are given in the
819 \code{pathconf_names
} dictionary. For configuration variables not
820 included in that mapping, passing an integer for
\var{name
} is also
824 If
\var{name
} is a string and is not known,
\exception{ValueError
} is
825 raised. If a specific value for
\var{name
} is not supported by the
826 host system, even if it is included in
\code{pathconf_names
}, an
827 \exception{OSError
} is raised with
\constant{errno.EINVAL
} for the
831 \begin{datadesc
}{pathconf_names
}
832 Dictionary mapping names accepted by
\function{pathconf()
} and
833 \function{fpathconf()
} to the integer values defined for those names
834 by the host operating system. This can be used to determine the set
835 of names known to the system.
839 \begin{funcdesc
}{readlink
}{path
}
840 Return a string representing the path to which the symbolic link
841 points. The result may be either an absolute or relative pathname; if
842 it is relative, it may be converted to an absolute pathname using
843 \code{os.path.join(os.path.dirname(
\var{path
}),
\var{result
})
}.
847 \begin{funcdesc
}{remove
}{path
}
848 Remove the file
\var{path
}. If
\var{path
} is a directory,
849 \exception{OSError
} is raised; see
\function{rmdir()
} below to remove
850 a directory. This is identical to the
\function{unlink()
} function
851 documented below. On Windows, attempting to remove a file that is in
852 use causes an exception to be raised; on
\UNIX, the directory entry is
853 removed but the storage allocated to the file is not made available
854 until the original file is no longer in use.
855 Availability: Macintosh,
\UNIX, Windows.
858 \begin{funcdesc
}{removedirs
}{path
}
859 \index{directory!deleting
}
860 Removes directories recursively. Works like
861 \function{rmdir()
} except that, if the leaf directory is
862 successfully removed, directories corresponding to rightmost path
863 segments will be pruned way until either the whole path is consumed or
864 an error is raised (which is ignored, because it generally means that
865 a parent directory is not empty). Throws an
\exception{error
}
866 exception if the leaf directory could not be successfully removed.
870 \begin{funcdesc
}{rename
}{src, dst
}
871 Rename the file or directory
\var{src
} to
\var{dst
}. If
\var{dst
} is
872 a directory,
\exception{OSError
} will be raised. On
\UNIX, if
873 \var{dst
} exists and is a file, it will be removed silently if the
874 user has permission. The operation may fail on some
\UNIX{} flavors
875 if
\var{src
} and
\var{dst
} are on different filesystems. If
876 successful, the renaming will be an atomic operation (this is a
877 \POSIX{} requirement). On Windows, if
\var{dst
} already exists,
878 \exception{OSError
} will be raised even if it is a file; there may be
879 no way to implement an atomic rename when
\var{dst
} names an existing
881 Availability: Macintosh,
\UNIX, Windows.
884 \begin{funcdesc
}{renames
}{old, new
}
885 Recursive directory or file renaming function.
886 Works like
\function{rename()
}, except creation of any intermediate
887 directories needed to make the new pathname good is attempted first.
888 After the rename, directories corresponding to rightmost path segments
889 of the old name will be pruned away using
\function{removedirs()
}.
893 This function can fail with the new directory structure made if
894 you lack permissions needed to remove the leaf directory or file.
898 \begin{funcdesc
}{rmdir
}{path
}
899 Remove the directory
\var{path
}.
900 Availability: Macintosh,
\UNIX, Windows.
903 \begin{funcdesc
}{stat
}{path
}
904 Perform a
\cfunction{stat()
} system call on the given path. The
905 return value is an object whose attributes correspond to the members of
906 the
\ctype{stat
} structure, namely:
907 \member{st_mode
} (protection bits),
908 \member{st_ino
} (inode number),
909 \member{st_dev
} (device),
910 \member{st_nlink
} (number of hard links),
911 \member{st_uid
} (user ID of owner),
912 \member{st_gid
} (group ID of owner),
913 \member{st_size
} (size of file, in bytes),
914 \member{st_atime
} (time of most recent access),
915 \member{st_mtime
} (time of most recent content modification),
917 (platform dependent; time of most recent metadata change on
\UNIX, or
918 the time of creation on Windows).
920 \versionchanged [If
\function{stat_float_times
} returns true, the time
921 values are floats, measuring seconds. Fractions of a second may be
922 reported if the system supports that. On Mac OS, the times are always
923 floats. See
\function{stat_float_times
} for further discussion.
]{2.3}
925 On some Unix systems (such as Linux), the following attributes may
927 \member{st_blocks
} (number of blocks allocated for file),
928 \member{st_blksize
} (filesystem blocksize),
929 \member{st_rdev
} (type of device if an inode device).
931 On Mac OS systems, the following attributes may also be available:
936 On RISCOS systems, the following attributes are also available:
937 \member{st_ftype
} (file type),
938 \member{st_attrs
} (attributes),
939 \member{st_obtype
} (object type).
941 For backward compatibility, the return value of
\function{stat()
} is
942 also accessible as a tuple of at least
10 integers giving the most
943 important (and portable) members of the
\ctype{stat
} structure, in the
955 More items may be added at the end by some implementations.
956 The standard module
\refmodule{stat
}\refstmodindex{stat
} defines
957 functions and constants that are useful for extracting information
958 from a
\ctype{stat
} structure.
959 (On Windows, some items are filled with dummy values.)
960 Availability: Macintosh,
\UNIX, Windows.
963 [Added access to values as attributes of the returned object
]{2.2}
966 \begin{funcdesc
}{stat_float_times
}{\optional{newvalue
}}
967 Determine whether
\class{stat_result
} represents time stamps as float
968 objects. If newval is True, future calls to stat() return floats, if
969 it is False, future calls return ints. If newval is omitted, return
972 For compatibility with older Python versions, accessing
973 \class{stat_result
} as a tuple always returns integers. For
974 compatibility with Python
2.2, accessing the time stamps by field name
975 also returns integers. Applications that want to determine the
976 fractions of a second in a time stamp can use this function to have
977 time stamps represented as floats. Whether they will actually observe
978 non-zero fractions depends on the system.
980 Future Python releases will change the default of this setting;
981 applications that cannot deal with floating point time stamps can then
982 use this function to turn the feature off.
984 It is recommended that this setting is only changed at program startup
985 time in the
\var{__main__
} module; libraries should never change this
986 setting. If an application uses a library that works incorrectly if
987 floating point time stamps are processed, this application should turn
988 the feature off until the library has been corrected.
992 \begin{funcdesc
}{statvfs
}{path
}
993 Perform a
\cfunction{statvfs()
} system call on the given path. The
994 return value is an object whose attributes describe the filesystem on
995 the given path, and correspond to the members of the
996 \ctype{statvfs
} structure, namely:
1006 Availability:
\UNIX.
1008 For backward compatibility, the return value is also accessible as a
1009 tuple whose values correspond to the attributes, in the order given above.
1010 The standard module
\refmodule{statvfs
}\refstmodindex{statvfs
}
1011 defines constants that are useful for extracting information
1012 from a
\ctype{statvfs
} structure when accessing it as a sequence; this
1013 remains useful when writing code that needs to work with versions of
1014 Python that don't support accessing the fields as attributes.
1017 [Added access to values as attributes of the returned object
]{2.2}
1020 \begin{funcdesc
}{symlink
}{src, dst
}
1021 Create a symbolic link pointing to
\var{src
} named
\var{dst
}.
1022 Availability:
\UNIX.
1025 \begin{funcdesc
}{tempnam
}{\optional{dir
\optional{, prefix
}}}
1026 Return a unique path name that is reasonable for creating a temporary
1027 file. This will be an absolute path that names a potential directory
1028 entry in the directory
\var{dir
} or a common location for temporary
1029 files if
\var{dir
} is omitted or
\code{None
}. If given and not
1030 \code{None
},
\var{prefix
} is used to provide a short prefix to the
1031 filename. Applications are responsible for properly creating and
1032 managing files created using paths returned by
\function{tempnam()
};
1033 no automatic cleanup is provided.
1034 On
\UNIX, the environment variable
\envvar{TMPDIR
} overrides
1035 \var{dir
}, while on Windows the
\envvar{TMP
} is used. The specific
1036 behavior of this function depends on the C library implementation;
1037 some aspects are underspecified in system documentation.
1038 \warning{Use of
\function{tempnam()
} is vulnerable to symlink attacks;
1039 consider using
\function{tmpfile()
} instead.
}
1040 Availability:
\UNIX, Windows.
1043 \begin{funcdesc
}{tmpnam
}{}
1044 Return a unique path name that is reasonable for creating a temporary
1045 file. This will be an absolute path that names a potential directory
1046 entry in a common location for temporary files. Applications are
1047 responsible for properly creating and managing files created using
1048 paths returned by
\function{tmpnam()
}; no automatic cleanup is
1050 \warning{Use of
\function{tmpnam()
} is vulnerable to symlink attacks;
1051 consider using
\function{tmpfile()
} instead.
}
1052 Availability:
\UNIX, Windows. This function probably shouldn't be used
1053 on Windows, though: Microsoft's implementation of
\function{tmpnam()
}
1054 always creates a name in the root directory of the current drive, and
1055 that's generally a poor location for a temp file (depending on
1056 privileges, you may not even be able to open a file using this name).
1059 \begin{datadesc
}{TMP_MAX
}
1060 The maximum number of unique names that
\function{tmpnam()
} will
1061 generate before reusing names.
1064 \begin{funcdesc
}{unlink
}{path
}
1065 Remove the file
\var{path
}. This is the same function as
1066 \function{remove()
}; the
\function{unlink()
} name is its traditional
1068 Availability: Macintosh,
\UNIX, Windows.
1071 \begin{funcdesc
}{utime
}{path, times
}
1072 Set the access and modified times of the file specified by
\var{path
}.
1073 If
\var{times
} is
\code{None
}, then the file's access and modified
1074 times are set to the current time. Otherwise,
\var{times
} must be a
1075 2-tuple of numbers, of the form
\code{(
\var{atime
},
\var{mtime
})
}
1076 which is used to set the access and modified times, respectively.
1077 \versionchanged[Added support for
\code{None
} for
\var{times
}]{2.0}
1078 Availability: Macintosh,
\UNIX, Windows.
1081 \begin{funcdesc
}{walk
}{top
\optional{, topdown
\code{=True
}
1082 \optional{, onerror
\code{=None
}}}}
1083 \index{directory!walking
}
1084 \index{directory!traversal
}
1085 \function{walk()
} generates the file names in a directory tree, by
1086 walking the tree either top down or bottom up.
1087 For each directory in the tree rooted at directory
\var{top
} (including
1088 \var{top
} itself), it yields a
3-tuple
1089 \code{(
\var{dirpath
},
\var{dirnames
},
\var{filenames
})
}.
1091 \var{dirpath
} is a string, the path to the directory.
\var{dirnames
} is
1092 a list of the names of the subdirectories in
\var{dirpath
}
1093 (excluding
\code{'.'
} and
\code{'..'
}).
\var{filenames
} is a list of
1094 the names of the non-directory files in
\var{dirpath
}. Note that the
1095 names in the lists contain no path components. To get a full
1096 path (which begins with
\var{top
}) to a file or directory in
1097 \var{dirpath
}, do
\code{os.path.join(
\var{dirpath
},
\var{name
})
}.
1099 If optional argument
\var{topdown
} is true or not specified, the triple
1100 for a directory is generated before the triples for any of its
1101 subdirectories (directories are generated top down). If
\var{topdown
} is
1102 false, the triple for a directory is generated after the triples for all
1103 of its subdirectories (directories are generated bottom up).
1105 When
\var{topdown
} is true, the caller can modify the
\var{dirnames
} list
1106 in-place (perhaps using
\keyword{del
} or slice assignment), and
1107 \function{walk()
} will only recurse into the subdirectories whose names
1108 remain in
\var{dirnames
}; this can be used to prune the search,
1109 impose a specific order of visiting, or even to inform
\function{walk()
}
1110 about directories the caller creates or renames before it resumes
1111 \function{walk()
} again. Modifying
\var{dirnames
} when
\var{topdown
} is
1112 false is ineffective, because in bottom-up mode the directories in
1113 \var{dirnames
} are generated before
\var{dirnames
} itself is generated.
1115 By default errors from the
\code{os.listdir()
} call are ignored. If
1116 optional argument
\var{onerror
} is specified, it should be a function;
1117 it will be called with one argument, an os.error instance. It can
1118 report the error to continue with the walk, or raise the exception
1119 to abort the walk. Note that the filename is available as the
1120 \code{filename
} attribute of the exception object.
1123 If you pass a relative pathname, don't change the current working
1124 directory between resumptions of
\function{walk()
}.
\function{walk()
}
1125 never changes the current directory, and assumes that its caller
1130 On systems that support symbolic links, links to subdirectories appear
1131 in
\var{dirnames
} lists, but
\function{walk()
} will not visit them
1132 (infinite loops are hard to avoid when following symbolic links).
1133 To visit linked directories, you can identify them with
1134 \code{os.path.islink(
\var{path
})
}, and invoke
\code{walk(
\var{path
})
}
1138 This example displays the number of bytes taken by non-directory files
1139 in each directory under the starting directory, except that it doesn't
1140 look under any CVS subdirectory:
1144 from os.path import join, getsize
1145 for root, dirs, files in os.walk('python/Lib/email'):
1146 print root, "consumes",
1147 print sum(
[getsize(join(root, name)) for name in files
]),
1148 print "bytes in", len(files), "non-directory files"
1150 dirs.remove('CVS') # don't visit CVS directories
1153 In the next example, walking the tree bottom up is essential:
1154 \function{rmdir()
} doesn't allow deleting a directory before the
1159 from os.path import join
1160 # Delete everything reachable from the directory named in 'top'.
1161 # CAUTION: This is dangerous! For example, if top == '/', it
1162 # could delete all your disk files.
1163 for root, dirs, files in os.walk(top, topdown=False):
1165 os.remove(join(root, name))
1167 os.rmdir(join(root, name))
1173 \subsection{Process Management
\label{os-process
}}
1175 These functions may be used to create and manage processes.
1177 The various
\function{exec*()
} functions take a list of arguments for
1178 the new program loaded into the process. In each case, the first of
1179 these arguments is passed to the new program as its own name rather
1180 than as an argument a user may have typed on a command line. For the
1181 C programmer, this is the
\code{argv
[0]} passed to a program's
1182 \cfunction{main()
}. For example,
\samp{os.execv('/bin/echo',
['foo',
1183 'bar'
])
} will only print
\samp{bar
} on standard output;
\samp{foo
}
1184 will seem to be ignored.
1187 \begin{funcdesc
}{abort
}{}
1188 Generate a
\constant{SIGABRT
} signal to the current process. On
1189 \UNIX, the default behavior is to produce a core dump; on Windows, the
1190 process immediately returns an exit code of
\code{3}. Be aware that
1191 programs which use
\function{signal.signal()
} to register a handler
1192 for
\constant{SIGABRT
} will behave differently.
1193 Availability:
\UNIX, Windows.
1196 \begin{funcdesc
}{execl
}{path, arg0, arg1,
\moreargs}
1197 \funcline{execle
}{path, arg0, arg1,
\moreargs, env
}
1198 \funcline{execlp
}{file, arg0, arg1,
\moreargs}
1199 \funcline{execlpe
}{file, arg0, arg1,
\moreargs, env
}
1200 \funcline{execv
}{path, args
}
1201 \funcline{execve
}{path, args, env
}
1202 \funcline{execvp
}{file, args
}
1203 \funcline{execvpe
}{file, args, env
}
1204 These functions all execute a new program, replacing the current
1205 process; they do not return. On
\UNIX, the new executable is loaded
1206 into the current process, and will have the same process ID as the
1207 caller. Errors will be reported as
\exception{OSError
} exceptions.
1209 The
\character{l
} and
\character{v
} variants of the
1210 \function{exec*()
} functions differ in how command-line arguments are
1211 passed. The
\character{l
} variants are perhaps the easiest to work
1212 with if the number of parameters is fixed when the code is written;
1213 the individual parameters simply become additional parameters to the
1214 \function{execl*()
} functions. The
\character{v
} variants are good
1215 when the number of parameters is variable, with the arguments being
1216 passed in a list or tuple as the
\var{args
} parameter. In either
1217 case, the arguments to the child process must start with the name of
1218 the command being run.
1220 The variants which include a
\character{p
} near the end
1221 (
\function{execlp()
},
\function{execlpe()
},
\function{execvp()
},
1222 and
\function{execvpe()
}) will use the
\envvar{PATH
} environment
1223 variable to locate the program
\var{file
}. When the environment is
1224 being replaced (using one of the
\function{exec*e()
} variants,
1225 discussed in the next paragraph), the
1226 new environment is used as the source of the
\envvar{PATH
} variable.
1227 The other variants,
\function{execl()
},
\function{execle()
},
1228 \function{execv()
}, and
\function{execve()
}, will not use the
1229 \envvar{PATH
} variable to locate the executable;
\var{path
} must
1230 contain an appropriate absolute or relative path.
1232 For
\function{execle()
},
\function{execlpe()
},
\function{execve()
},
1233 and
\function{execvpe()
} (note that these all end in
\character{e
}),
1234 the
\var{env
} parameter must be a mapping which is used to define the
1235 environment variables for the new process; the
\function{execl()
},
1236 \function{execlp()
},
\function{execv()
}, and
\function{execvp()
}
1237 all cause the new process to inherit the environment of the current
1239 Availability:
\UNIX, Windows.
1242 \begin{funcdesc
}{_exit
}{n
}
1243 Exit to the system with status
\var{n
}, without calling cleanup
1244 handlers, flushing stdio buffers, etc.
1245 Availability:
\UNIX, Windows.
1248 The standard way to exit is
\code{sys.exit(
\var{n
})
}.
1249 \function{_exit()
} should normally only be used in the child process
1250 after a
\function{fork()
}.
1254 The following exit codes are a defined, and can be used with
1255 \function{_exit()
}, although they are not required. These are
1256 typically used for system programs written in Python, such as a
1257 mail server's external command delivery program.
1259 \begin{datadesc
}{EX_OK
}
1260 Exit code that means no error occurred.
1261 Availability:
\UNIX.
1265 \begin{datadesc
}{EX_USAGE
}
1266 Exit code that means the command was used incorrectly, such as when
1267 the wrong number of arguments are given.
1268 Availability:
\UNIX.
1272 \begin{datadesc
}{EX_DATAERR
}
1273 Exit code that means the input data was incorrect.
1274 Availability:
\UNIX.
1278 \begin{datadesc
}{EX_NOINPUT
}
1279 Exit code that means an input file did not exist or was not readable.
1280 Availability:
\UNIX.
1284 \begin{datadesc
}{EX_NOUSER
}
1285 Exit code that means a specified user did not exist.
1286 Availability:
\UNIX.
1290 \begin{datadesc
}{EX_NOHOST
}
1291 Exit code that means a specified host did not exist.
1292 Availability:
\UNIX.
1296 \begin{datadesc
}{EX_UNAVAILABLE
}
1297 Exit code that means that a required service is unavailable.
1298 Availability:
\UNIX.
1302 \begin{datadesc
}{EX_SOFTWARE
}
1303 Exit code that means an internal software error was detected.
1304 Availability:
\UNIX.
1308 \begin{datadesc
}{EX_OSERR
}
1309 Exit code that means an operating system error was detected, such as
1310 the inability to fork or create a pipe.
1311 Availability:
\UNIX.
1315 \begin{datadesc
}{EX_OSFILE
}
1316 Exit code that means some system file did not exist, could not be
1317 opened, or had some other kind of error.
1318 Availability:
\UNIX.
1322 \begin{datadesc
}{EX_CANTCREAT
}
1323 Exit code that means a user specified output file could not be created.
1324 Availability:
\UNIX.
1328 \begin{datadesc
}{EX_IOERR
}
1329 Exit code that means that an error occurred while doing I/O on some file.
1330 Availability:
\UNIX.
1334 \begin{datadesc
}{EX_TEMPFAIL
}
1335 Exit code that means a temporary failure occurred. This indicates
1336 something that may not really be an error, such as a network
1337 connection that couldn't be made during a retryable operation.
1338 Availability:
\UNIX.
1342 \begin{datadesc
}{EX_PROTOCOL
}
1343 Exit code that means that a protocol exchange was illegal, invalid, or
1345 Availability:
\UNIX.
1349 \begin{datadesc
}{EX_NOPERM
}
1350 Exit code that means that there were insufficient permissions to
1351 perform the operation (but not intended for file system problems).
1352 Availability:
\UNIX.
1356 \begin{datadesc
}{EX_CONFIG
}
1357 Exit code that means that some kind of configuration error occurred.
1358 Availability:
\UNIX.
1362 \begin{datadesc
}{EX_NOTFOUND
}
1363 Exit code that means something like ``an entry was not found''.
1364 Availability:
\UNIX.
1368 \begin{funcdesc
}{fork
}{}
1369 Fork a child process. Return
\code{0} in the child, the child's
1370 process id in the parent.
1371 Availability:
\UNIX.
1374 \begin{funcdesc
}{forkpty
}{}
1375 Fork a child process, using a new pseudo-terminal as the child's
1376 controlling terminal. Return a pair of
\code{(
\var{pid
},
\var{fd
})
},
1377 where
\var{pid
} is
\code{0} in the child, the new child's process id
1378 in the parent, and
\var{fd
} is the file descriptor of the master end
1379 of the pseudo-terminal. For a more portable approach, use the
1380 \refmodule{pty
} module.
1381 Availability: Some flavors of
\UNIX.
1384 \begin{funcdesc
}{kill
}{pid, sig
}
1385 \index{process!killing
}
1386 \index{process!signalling
}
1387 Kill the process
\var{pid
} with signal
\var{sig
}. Constants for the
1388 specific signals available on the host platform are defined in the
1389 \refmodule{signal
} module.
1390 Availability:
\UNIX.
1393 \begin{funcdesc
}{killpg
}{pgid, sig
}
1394 \index{process!killing
}
1395 \index{process!signalling
}
1396 Kill the process group
\var{pgid
} with the signal
\var{sig
}.
1397 Availability:
\UNIX.
1401 \begin{funcdesc
}{nice
}{increment
}
1402 Add
\var{increment
} to the process's ``niceness''. Return the new
1404 Availability:
\UNIX.
1407 \begin{funcdesc
}{plock
}{op
}
1408 Lock program segments into memory. The value of
\var{op
}
1409 (defined in
\code{<sys/lock.h>
}) determines which segments are locked.
1410 Availability:
\UNIX.
1413 \begin{funcdescni
}{popen
}{\unspecified}
1414 \funclineni{popen2
}{\unspecified}
1415 \funclineni{popen3
}{\unspecified}
1416 \funclineni{popen4
}{\unspecified}
1417 Run child processes, returning opened pipes for communications. These
1418 functions are described in section
\ref{os-newstreams
}.
1421 \begin{funcdesc
}{spawnl
}{mode, path,
\moreargs}
1422 \funcline{spawnle
}{mode, path,
\moreargs, env
}
1423 \funcline{spawnlp
}{mode, file,
\moreargs}
1424 \funcline{spawnlpe
}{mode, file,
\moreargs, env
}
1425 \funcline{spawnv
}{mode, path, args
}
1426 \funcline{spawnve
}{mode, path, args, env
}
1427 \funcline{spawnvp
}{mode, file, args
}
1428 \funcline{spawnvpe
}{mode, file, args, env
}
1429 Execute the program
\var{path
} in a new process. If
\var{mode
} is
1430 \constant{P_NOWAIT
}, this function returns the process ID of the new
1431 process; if
\var{mode
} is
\constant{P_WAIT
}, returns the process's
1432 exit code if it exits normally, or
\code{-
\var{signal
}}, where
1433 \var{signal
} is the signal that killed the process. On Windows, the
1434 process ID will actually be the process handle, so can be used with
1435 the
\function{waitpid()
} function.
1437 The
\character{l
} and
\character{v
} variants of the
1438 \function{spawn*()
} functions differ in how command-line arguments are
1439 passed. The
\character{l
} variants are perhaps the easiest to work
1440 with if the number of parameters is fixed when the code is written;
1441 the individual parameters simply become additional parameters to the
1442 \function{spawnl*()
} functions. The
\character{v
} variants are good
1443 when the number of parameters is variable, with the arguments being
1444 passed in a list or tuple as the
\var{args
} parameter. In either
1445 case, the arguments to the child process must start with the name of
1446 the command being run.
1448 The variants which include a second
\character{p
} near the end
1449 (
\function{spawnlp()
},
\function{spawnlpe()
},
\function{spawnvp()
},
1450 and
\function{spawnvpe()
}) will use the
\envvar{PATH
} environment
1451 variable to locate the program
\var{file
}. When the environment is
1452 being replaced (using one of the
\function{spawn*e()
} variants,
1453 discussed in the next paragraph), the new environment is used as the
1454 source of the
\envvar{PATH
} variable. The other variants,
1455 \function{spawnl()
},
\function{spawnle()
},
\function{spawnv()
}, and
1456 \function{spawnve()
}, will not use the
\envvar{PATH
} variable to
1457 locate the executable;
\var{path
} must contain an appropriate absolute
1460 For
\function{spawnle()
},
\function{spawnlpe()
},
\function{spawnve()
},
1461 and
\function{spawnvpe()
} (note that these all end in
\character{e
}),
1462 the
\var{env
} parameter must be a mapping which is used to define the
1463 environment variables for the new process; the
\function{spawnl()
},
1464 \function{spawnlp()
},
\function{spawnv()
}, and
\function{spawnvp()
}
1465 all cause the new process to inherit the environment of the current
1468 As an example, the following calls to
\function{spawnlp()
} and
1469 \function{spawnvpe()
} are equivalent:
1473 os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null')
1475 L =
['cp', 'index.html', '/dev/null'
]
1476 os.spawnvpe(os.P_WAIT, 'cp', L, os.environ)
1479 Availability:
\UNIX, Windows.
\function{spawnlp()
},
1480 \function{spawnlpe()
},
\function{spawnvp()
} and
\function{spawnvpe()
}
1481 are not available on Windows.
1485 \begin{datadesc
}{P_NOWAIT
}
1486 \dataline{P_NOWAITO
}
1487 Possible values for the
\var{mode
} parameter to the
\function{spawn*()
}
1488 family of functions. If either of these values is given, the
1489 \function{spawn*()
} functions will return as soon as the new process
1490 has been created, with the process ID as the return value.
1491 Availability:
\UNIX, Windows.
1495 \begin{datadesc
}{P_WAIT
}
1496 Possible value for the
\var{mode
} parameter to the
\function{spawn*()
}
1497 family of functions. If this is given as
\var{mode
}, the
1498 \function{spawn*()
} functions will not return until the new process
1499 has run to completion and will return the exit code of the process the
1500 run is successful, or
\code{-
\var{signal
}} if a signal kills the
1502 Availability:
\UNIX, Windows.
1506 \begin{datadesc
}{P_DETACH
}
1507 \dataline{P_OVERLAY
}
1508 Possible values for the
\var{mode
} parameter to the
1509 \function{spawn*()
} family of functions. These are less portable than
1511 \constant{P_DETACH
} is similar to
\constant{P_NOWAIT
}, but the new
1512 process is detached from the console of the calling process.
1513 If
\constant{P_OVERLAY
} is used, the current process will be replaced;
1514 the
\function{spawn*()
} function will not return.
1515 Availability: Windows.
1519 \begin{funcdesc
}{startfile
}{path
}
1520 Start a file with its associated application. This acts like
1521 double-clicking the file in Windows Explorer, or giving the file name
1522 as an argument to the
\program{start
} command from the interactive
1523 command shell: the file is opened with whatever application (if any)
1524 its extension is associated.
1526 \function{startfile()
} returns as soon as the associated application
1527 is launched. There is no option to wait for the application to close,
1528 and no way to retrieve the application's exit status. The
\var{path
}
1529 parameter is relative to the current directory. If you want to use an
1530 absolute path, make sure the first character is not a slash
1531 (
\character{/
}); the underlying Win32
\cfunction{ShellExecute()
}
1532 function doesn't work if it is. Use the
\function{os.path.normpath()
}
1533 function to ensure that the path is properly encoded for Win32.
1534 Availability: Windows.
1538 \begin{funcdesc
}{system
}{command
}
1539 Execute the command (a string) in a subshell. This is implemented by
1540 calling the Standard C function
\cfunction{system()
}, and has the
1541 same limitations. Changes to
\code{posix.environ
},
\code{sys.stdin
},
1542 etc.\ are not reflected in the environment of the executed command.
1544 On
\UNIX, the return value is the exit status of the process encoded in the
1545 format specified for
\function{wait()
}. Note that
\POSIX{} does not
1546 specify the meaning of the return value of the C
\cfunction{system()
}
1547 function, so the return value of the Python function is system-dependent.
1549 On Windows, the return value is that returned by the system shell after
1550 running
\var{command
}, given by the Windows environment variable
1551 \envvar{COMSPEC
}: on
\program{command.com
} systems (Windows
95,
98 and ME)
1552 this is always
\code{0}; on
\program{cmd.exe
} systems (Windows NT,
2000
1553 and XP) this is the exit status of the command run; on systems using
1554 a non-native shell, consult your shell documentation.
1556 Availability:
\UNIX, Windows.
1559 \begin{funcdesc
}{times
}{}
1560 Return a
5-tuple of floating point numbers indicating accumulated
1561 (processor or other)
1562 times, in seconds. The items are: user time, system time, children's
1563 user time, children's system time, and elapsed real time since a fixed
1564 point in the past, in that order. See the
\UNIX{} manual page
1565 \manpage{times
}{2} or the corresponding Windows Platform API
1567 Availability:
\UNIX, Windows.
1570 \begin{funcdesc
}{wait
}{}
1571 Wait for completion of a child process, and return a tuple containing
1572 its pid and exit status indication: a
16-bit number, whose low byte is
1573 the signal number that killed the process, and whose high byte is the
1574 exit status (if the signal number is zero); the high bit of the low
1575 byte is set if a core file was produced.
1576 Availability:
\UNIX.
1579 \begin{funcdesc
}{waitpid
}{pid, options
}
1580 The details of this function differ on
\UNIX{} and Windows.
1583 Wait for completion of a child process given by process id
\var{pid
},
1584 and return a tuple containing its process id and exit status
1585 indication (encoded as for
\function{wait()
}). The semantics of the
1586 call are affected by the value of the integer
\var{options
}, which
1587 should be
\code{0} for normal operation.
1589 If
\var{pid
} is greater than
\code{0},
\function{waitpid()
} requests
1590 status information for that specific process. If
\var{pid
} is
1591 \code{0}, the request is for the status of any child in the process
1592 group of the current process. If
\var{pid
} is
\code{-
1}, the request
1593 pertains to any child of the current process. If
\var{pid
} is less
1594 than
\code{-
1}, status is requested for any process in the process
1595 group
\code{-
\var{pid
}} (the absolute value of
\var{pid
}).
1598 Wait for completion of a process given by process handle
\var{pid
},
1599 and return a tuple containing
\var{pid
},
1600 and its exit status shifted left by
8 bits (shifting makes cross-platform
1601 use of the function easier).
1602 A
\var{pid
} less than or equal to
\code{0} has no special meaning on
1603 Windows, and raises an exception.
1604 The value of integer
\var{options
} has no effect.
1605 \var{pid
} can refer to any process whose id is known, not necessarily a
1607 The
\function{spawn()
} functions called with
\constant{P_NOWAIT
}
1608 return suitable process handles.
1611 \begin{datadesc
}{WNOHANG
}
1612 The option for
\function{waitpid()
} to avoid hanging if no child
1613 process status is available immediately.
1614 Availability:
\UNIX.
1617 \begin{datadesc
}{WCONTINUED
}
1618 This option causes child processes to be reported if they have been
1619 continued from a job control stop since their status was last
1621 Availability: Some
\UNIX{} systems.
1625 \begin{datadesc
}{WUNTRACED
}
1626 This option causes child processes to be reported if they have been
1627 stopped but their current state has not been reported since they were
1629 Availability:
\UNIX.
1633 The following functions take a process status code as returned by
1634 \function{system()
},
\function{wait()
}, or
\function{waitpid()
} as a
1635 parameter. They may be used to determine the disposition of a
1638 \begin{funcdesc
}{WCOREDUMP
}{status
}
1639 Returns
\code{True
} if a core dump was generated for the process,
1640 otherwise it returns
\code{False
}.
1641 Availability:
\UNIX.
1645 \begin{funcdesc
}{WIFCONTINUED
}{status
}
1646 Returns
\code{True
} if the process has been continued from a job
1647 control stop, otherwise it returns
\code{False
}.
1648 Availability:
\UNIX.
1652 \begin{funcdesc
}{WIFSTOPPED
}{status
}
1653 Returns
\code{True
} if the process has been stopped, otherwise it
1654 returns
\code{False
}.
1655 Availability:
\UNIX.
1658 \begin{funcdesc
}{WIFSIGNALED
}{status
}
1659 Returns
\code{True
} if the process exited due to a signal, otherwise
1660 it returns
\code{False
}.
1661 Availability:
\UNIX.
1664 \begin{funcdesc
}{WIFEXITED
}{status
}
1665 Returns
\code{True
} if the process exited using the
\manpage{exit
}{2}
1666 system call, otherwise it returns
\code{False
}.
1667 Availability:
\UNIX.
1670 \begin{funcdesc
}{WEXITSTATUS
}{status
}
1671 If
\code{WIFEXITED(
\var{status
})
} is true, return the integer
1672 parameter to the
\manpage{exit
}{2} system call. Otherwise, the return
1673 value is meaningless.
1674 Availability:
\UNIX.
1677 \begin{funcdesc
}{WSTOPSIG
}{status
}
1678 Return the signal which caused the process to stop.
1679 Availability:
\UNIX.
1682 \begin{funcdesc
}{WTERMSIG
}{status
}
1683 Return the signal which caused the process to exit.
1684 Availability:
\UNIX.
1688 \subsection{Miscellaneous System Information
\label{os-path
}}
1691 \begin{funcdesc
}{confstr
}{name
}
1692 Return string-valued system configuration values.
1693 \var{name
} specifies the configuration value to retrieve; it may be a
1694 string which is the name of a defined system value; these names are
1695 specified in a number of standards (
\POSIX,
\UNIX{} 95,
\UNIX{} 98, and
1696 others). Some platforms define additional names as well. The names
1697 known to the host operating system are given in the
1698 \code{confstr_names
} dictionary. For configuration variables not
1699 included in that mapping, passing an integer for
\var{name
} is also
1701 Availability:
\UNIX.
1703 If the configuration value specified by
\var{name
} isn't defined, the
1704 empty string is returned.
1706 If
\var{name
} is a string and is not known,
\exception{ValueError
} is
1707 raised. If a specific value for
\var{name
} is not supported by the
1708 host system, even if it is included in
\code{confstr_names
}, an
1709 \exception{OSError
} is raised with
\constant{errno.EINVAL
} for the
1713 \begin{datadesc
}{confstr_names
}
1714 Dictionary mapping names accepted by
\function{confstr()
} to the
1715 integer values defined for those names by the host operating system.
1716 This can be used to determine the set of names known to the system.
1717 Availability:
\UNIX.
1720 \begin{funcdesc
}{getloadavg
}{}
1721 Return the number of processes in the system run queue averaged over
1722 the last
1,
5, and
15 minutes or raises OSError if the load average
1728 \begin{funcdesc
}{sysconf
}{name
}
1729 Return integer-valued system configuration values.
1730 If the configuration value specified by
\var{name
} isn't defined,
1731 \code{-
1} is returned. The comments regarding the
\var{name
}
1732 parameter for
\function{confstr()
} apply here as well; the dictionary
1733 that provides information on the known names is given by
1734 \code{sysconf_names
}.
1735 Availability:
\UNIX.
1738 \begin{datadesc
}{sysconf_names
}
1739 Dictionary mapping names accepted by
\function{sysconf()
} to the
1740 integer values defined for those names by the host operating system.
1741 This can be used to determine the set of names known to the system.
1742 Availability:
\UNIX.
1746 The follow data values are used to support path manipulation
1747 operations. These are defined for all platforms.
1749 Higher-level operations on pathnames are defined in the
1750 \refmodule{os.path
} module.
1753 \begin{datadesc
}{curdir
}
1754 The constant string used by the operating system to refer to the current
1756 For example:
\code{'.'
} for
\POSIX{} or
\code{':'
} for the Macintosh.
1757 Also available via
\module{os.path
}.
1760 \begin{datadesc
}{pardir
}
1761 The constant string used by the operating system to refer to the parent
1763 For example:
\code{'..'
} for
\POSIX{} or
\code{'::'
} for the Macintosh.
1764 Also available via
\module{os.path
}.
1767 \begin{datadesc
}{sep
}
1768 The character used by the operating system to separate pathname components,
1769 for example,
\character{/
} for
\POSIX{} or
\character{:
} for the
1770 Macintosh. Note that knowing this is not sufficient to be able to
1771 parse or concatenate pathnames --- use
\function{os.path.split()
} and
1772 \function{os.path.join()
} --- but it is occasionally useful.
1773 Also available via
\module{os.path
}.
1776 \begin{datadesc
}{altsep
}
1777 An alternative character used by the operating system to separate pathname
1778 components, or
\code{None
} if only one separator character exists. This is
1779 set to
\character{/
} on Windows systems where
\code{sep
} is a
1781 Also available via
\module{os.path
}.
1784 \begin{datadesc
}{extsep
}
1785 The character which separates the base filename from the extension;
1786 for example, the
\character{.
} in
\file{os.py
}.
1787 Also available via
\module{os.path
}.
1791 \begin{datadesc
}{pathsep
}
1792 The character conventionally used by the operating system to separate
1793 search patch components (as in
\envvar{PATH
}), such as
\character{:
} for
1794 \POSIX{} or
\character{;
} for Windows.
1795 Also available via
\module{os.path
}.
1798 \begin{datadesc
}{defpath
}
1799 The default search path used by
\function{exec*p*()
} and
1800 \function{spawn*p*()
} if the environment doesn't have a
\code{'PATH'
}
1802 Also available via
\module{os.path
}.
1805 \begin{datadesc
}{linesep
}
1806 The string used to separate (or, rather, terminate) lines on the
1807 current platform. This may be a single character, such as
\code{'
\e
1808 n'
} for
\POSIX{} or
\code{'
\e r'
} for Mac OS, or multiple characters,
1809 for example,
\code{'
\e r
\e n'
} for Windows.
1812 \begin{datadesc
}{devnull
}
1813 The file path of the null device.
1814 For example:
\code{'/dev/null'
} for
\POSIX{} or
\code{'Dev:Nul'
} for the
1816 Also available via
\module{os.path
}.