doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
os.spawnl(mode, path, ...) os.spawnle(mode, path, ..., env) os.spawnlp(mode, file, ...) os.spawnlpe(mode, file, ..., env) os.spawnv(mode, path, args) os.spawnve(mode, path, args, env) os.spawnvp(mode, file, args) os.spawnvpe(mode, file, args, env) Execute the program path in a new process. (Note that the subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using these functions. Check especially the Replacing Older Functions with the subprocess Module section.) If mode is P_NOWAIT, this function returns the process id of the new process; if mode is P_WAIT, returns the process’s exit code if it exits normally, or -signal, where signal is the signal that killed the process. On Windows, the process id will actually be the process handle, so can be used with the waitpid() function. Note on VxWorks, this function doesn’t return -signal when the new process is killed. Instead it raises OSError exception. The “l” and “v” variants of the spawn* functions differ in how command-line arguments are passed. The “l” variants are perhaps the easiest to work with if the number of parameters is fixed when the code is written; the individual parameters simply become additional parameters to the spawnl*() functions. The “v” variants are good when the number of parameters is variable, with the arguments being passed in a list or tuple as the args parameter. In either case, the arguments to the child process must start with the name of the command being run. The variants which include a second “p” near the end (spawnlp(), spawnlpe(), spawnvp(), and spawnvpe()) will use the PATH environment variable to locate the program file. When the environment is being replaced (using one of the spawn*e variants, discussed in the next paragraph), the new environment is used as the source of the PATH variable. The other variants, spawnl(), spawnle(), spawnv(), and spawnve(), will not use the PATH variable to locate the executable; path must contain an appropriate absolute or relative path. For spawnle(), spawnlpe(), spawnve(), and spawnvpe() (note that these all end in “e”), the env parameter must be a mapping which is used to define the environment variables for the new process (they are used instead of the current process’ environment); the functions spawnl(), spawnlp(), spawnv(), and spawnvp() all cause the new process to inherit the environment of the current process. Note that keys and values in the env dictionary must be strings; invalid keys or values will cause the function to fail, with a return value of 127. As an example, the following calls to spawnlp() and spawnvpe() are equivalent: import os os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null') L = ['cp', 'index.html', '/dev/null'] os.spawnvpe(os.P_WAIT, 'cp', L, os.environ) Raises an auditing event os.spawn with arguments mode, path, args, env. Availability: Unix, Windows. spawnlp(), spawnlpe(), spawnvp() and spawnvpe() are not available on Windows. spawnle() and spawnve() are not thread-safe on Windows; we advise you to use the subprocess module instead. Changed in version 3.6: Accepts a path-like object.
python.library.os#os.spawnvp
os.spawnl(mode, path, ...) os.spawnle(mode, path, ..., env) os.spawnlp(mode, file, ...) os.spawnlpe(mode, file, ..., env) os.spawnv(mode, path, args) os.spawnve(mode, path, args, env) os.spawnvp(mode, file, args) os.spawnvpe(mode, file, args, env) Execute the program path in a new process. (Note that the subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using these functions. Check especially the Replacing Older Functions with the subprocess Module section.) If mode is P_NOWAIT, this function returns the process id of the new process; if mode is P_WAIT, returns the process’s exit code if it exits normally, or -signal, where signal is the signal that killed the process. On Windows, the process id will actually be the process handle, so can be used with the waitpid() function. Note on VxWorks, this function doesn’t return -signal when the new process is killed. Instead it raises OSError exception. The “l” and “v” variants of the spawn* functions differ in how command-line arguments are passed. The “l” variants are perhaps the easiest to work with if the number of parameters is fixed when the code is written; the individual parameters simply become additional parameters to the spawnl*() functions. The “v” variants are good when the number of parameters is variable, with the arguments being passed in a list or tuple as the args parameter. In either case, the arguments to the child process must start with the name of the command being run. The variants which include a second “p” near the end (spawnlp(), spawnlpe(), spawnvp(), and spawnvpe()) will use the PATH environment variable to locate the program file. When the environment is being replaced (using one of the spawn*e variants, discussed in the next paragraph), the new environment is used as the source of the PATH variable. The other variants, spawnl(), spawnle(), spawnv(), and spawnve(), will not use the PATH variable to locate the executable; path must contain an appropriate absolute or relative path. For spawnle(), spawnlpe(), spawnve(), and spawnvpe() (note that these all end in “e”), the env parameter must be a mapping which is used to define the environment variables for the new process (they are used instead of the current process’ environment); the functions spawnl(), spawnlp(), spawnv(), and spawnvp() all cause the new process to inherit the environment of the current process. Note that keys and values in the env dictionary must be strings; invalid keys or values will cause the function to fail, with a return value of 127. As an example, the following calls to spawnlp() and spawnvpe() are equivalent: import os os.spawnlp(os.P_WAIT, 'cp', 'cp', 'index.html', '/dev/null') L = ['cp', 'index.html', '/dev/null'] os.spawnvpe(os.P_WAIT, 'cp', L, os.environ) Raises an auditing event os.spawn with arguments mode, path, args, env. Availability: Unix, Windows. spawnlp(), spawnlpe(), spawnvp() and spawnvpe() are not available on Windows. spawnle() and spawnve() are not thread-safe on Windows; we advise you to use the subprocess module instead. Changed in version 3.6: Accepts a path-like object.
python.library.os#os.spawnvpe
os.startfile(path[, operation]) Start a file with its associated application. When operation is not specified or 'open', this acts like double-clicking the file in Windows Explorer, or giving the file name as an argument to the start command from the interactive command shell: the file is opened with whatever application (if any) its extension is associated. When another operation is given, it must be a “command verb” that specifies what should be done with the file. Common verbs documented by Microsoft are 'print' and 'edit' (to be used on files) as well as 'explore' and 'find' (to be used on directories). startfile() returns as soon as the associated application is launched. There is no option to wait for the application to close, and no way to retrieve the application’s exit status. The path parameter is relative to the current directory. If you want to use an absolute path, make sure the first character is not a slash ('/'); the underlying Win32 ShellExecute() function doesn’t work if it is. Use the os.path.normpath() function to ensure that the path is properly encoded for Win32. To reduce interpreter startup overhead, the Win32 ShellExecute() function is not resolved until this function is first called. If the function cannot be resolved, NotImplementedError will be raised. Raises an auditing event os.startfile with arguments path, operation. Availability: Windows.
python.library.os#os.startfile
os.stat(path, *, dir_fd=None, follow_symlinks=True) Get the status of a file or a file descriptor. Perform the equivalent of a stat() system call on the given path. path may be specified as either a string or bytes – directly or indirectly through the PathLike interface – or as an open file descriptor. Return a stat_result object. This function normally follows symlinks; to stat a symlink add the argument follow_symlinks=False, or use lstat(). This function can support specifying a file descriptor and not following symlinks. On Windows, passing follow_symlinks=False will disable following all name-surrogate reparse points, which includes symlinks and directory junctions. Other types of reparse points that do not resemble links or that the operating system is unable to follow will be opened directly. When following a chain of multiple links, this may result in the original link being returned instead of the non-link that prevented full traversal. To obtain stat results for the final path in this case, use the os.path.realpath() function to resolve the path name as far as possible and call lstat() on the result. This does not apply to dangling symlinks or junction points, which will raise the usual exceptions. Example: >>> import os >>> statinfo = os.stat('somefile.txt') >>> statinfo os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026, st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295, st_mtime=1297230027, st_ctime=1297230027) >>> statinfo.st_size 264 See also fstat() and lstat() functions. New in version 3.3: Added the dir_fd and follow_symlinks arguments, specifying a file descriptor instead of a path. Changed in version 3.6: Accepts a path-like object. Changed in version 3.8: On Windows, all reparse points that can be resolved by the operating system are now followed, and passing follow_symlinks=False disables following all name surrogate reparse points. If the operating system reaches a reparse point that it is not able to follow, stat now returns the information for the original path as if follow_symlinks=False had been specified instead of raising an error.
python.library.os#os.stat
os.statvfs(path) Perform a statvfs() system call on the given path. The return value is an object whose attributes describe the filesystem on the given path, and correspond to the members of the statvfs structure, namely: f_bsize, f_frsize, f_blocks, f_bfree, f_bavail, f_files, f_ffree, f_favail, f_flag, f_namemax, f_fsid. Two module-level constants are defined for the f_flag attribute’s bit-flags: if ST_RDONLY is set, the filesystem is mounted read-only, and if ST_NOSUID is set, the semantics of setuid/setgid bits are disabled or not supported. Additional module-level constants are defined for GNU/glibc based systems. These are ST_NODEV (disallow access to device special files), ST_NOEXEC (disallow program execution), ST_SYNCHRONOUS (writes are synced at once), ST_MANDLOCK (allow mandatory locks on an FS), ST_WRITE (write on file/directory/symlink), ST_APPEND (append-only file), ST_IMMUTABLE (immutable file), ST_NOATIME (do not update access times), ST_NODIRATIME (do not update directory access times), ST_RELATIME (update atime relative to mtime/ctime). This function can support specifying a file descriptor. Availability: Unix. Changed in version 3.2: The ST_RDONLY and ST_NOSUID constants were added. New in version 3.3: Added support for specifying path as an open file descriptor. Changed in version 3.4: The ST_NODEV, ST_NOEXEC, ST_SYNCHRONOUS, ST_MANDLOCK, ST_WRITE, ST_APPEND, ST_IMMUTABLE, ST_NOATIME, ST_NODIRATIME, and ST_RELATIME constants were added. Changed in version 3.6: Accepts a path-like object. New in version 3.7: Added f_fsid.
python.library.os#os.statvfs
class os.stat_result Object whose attributes correspond roughly to the members of the stat structure. It is used for the result of os.stat(), os.fstat() and os.lstat(). Attributes: st_mode File mode: file type and file mode bits (permissions). st_ino Platform dependent, but if non-zero, uniquely identifies the file for a given value of st_dev. Typically: the inode number on Unix, the file index on Windows st_dev Identifier of the device on which this file resides. st_nlink Number of hard links. st_uid User identifier of the file owner. st_gid Group identifier of the file owner. st_size Size of the file in bytes, if it is a regular file or a symbolic link. The size of a symbolic link is the length of the pathname it contains, without a terminating null byte. Timestamps: st_atime Time of most recent access expressed in seconds. st_mtime Time of most recent content modification expressed in seconds. st_ctime Platform dependent: the time of most recent metadata change on Unix, the time of creation on Windows, expressed in seconds. st_atime_ns Time of most recent access expressed in nanoseconds as an integer. st_mtime_ns Time of most recent content modification expressed in nanoseconds as an integer. st_ctime_ns Platform dependent: the time of most recent metadata change on Unix, the time of creation on Windows, expressed in nanoseconds as an integer. Note The exact meaning and resolution of the st_atime, st_mtime, and st_ctime attributes depend on the operating system and the file system. For example, on Windows systems using the FAT or FAT32 file systems, st_mtime has 2-second resolution, and st_atime has only 1-day resolution. See your operating system documentation for details. Similarly, although st_atime_ns, st_mtime_ns, and st_ctime_ns are always expressed in nanoseconds, many systems do not provide nanosecond precision. On systems that do provide nanosecond precision, the floating-point object used to store st_atime, st_mtime, and st_ctime cannot preserve all of it, and as such will be slightly inexact. If you need the exact timestamps you should always use st_atime_ns, st_mtime_ns, and st_ctime_ns. On some Unix systems (such as Linux), the following attributes may also be available: st_blocks Number of 512-byte blocks allocated for file. This may be smaller than st_size/512 when the file has holes. st_blksize “Preferred” blocksize for efficient file system I/O. Writing to a file in smaller chunks may cause an inefficient read-modify-rewrite. st_rdev Type of device if an inode device. st_flags User defined flags for file. On other Unix systems (such as FreeBSD), the following attributes may be available (but may be only filled out if root tries to use them): st_gen File generation number. st_birthtime Time of file creation. On Solaris and derivatives, the following attributes may also be available: st_fstype String that uniquely identifies the type of the filesystem that contains the file. On Mac OS systems, the following attributes may also be available: st_rsize Real size of the file. st_creator Creator of the file. st_type File type. On Windows systems, the following attributes are also available: st_file_attributes Windows file attributes: dwFileAttributes member of the BY_HANDLE_FILE_INFORMATION structure returned by GetFileInformationByHandle(). See the FILE_ATTRIBUTE_* constants in the stat module. st_reparse_tag When st_file_attributes has the FILE_ATTRIBUTE_REPARSE_POINT set, this field contains the tag identifying the type of reparse point. See the IO_REPARSE_TAG_* constants in the stat module. The standard module stat defines functions and constants that are useful for extracting information from a stat structure. (On Windows, some items are filled with dummy values.) For backward compatibility, a stat_result instance is also accessible as a tuple of at least 10 integers giving the most important (and portable) members of the stat structure, in the order st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid, st_size, st_atime, st_mtime, st_ctime. More items may be added at the end by some implementations. For compatibility with older Python versions, accessing stat_result as a tuple always returns integers. New in version 3.3: Added the st_atime_ns, st_mtime_ns, and st_ctime_ns members. New in version 3.5: Added the st_file_attributes member on Windows. Changed in version 3.5: Windows now returns the file index as st_ino when available. New in version 3.7: Added the st_fstype member to Solaris/derivatives. New in version 3.8: Added the st_reparse_tag member on Windows. Changed in version 3.8: On Windows, the st_mode member now identifies special files as S_IFCHR, S_IFIFO or S_IFBLK as appropriate.
python.library.os#os.stat_result
st_atime Time of most recent access expressed in seconds.
python.library.os#os.stat_result.st_atime
st_atime_ns Time of most recent access expressed in nanoseconds as an integer.
python.library.os#os.stat_result.st_atime_ns
st_birthtime Time of file creation.
python.library.os#os.stat_result.st_birthtime
st_blksize “Preferred” blocksize for efficient file system I/O. Writing to a file in smaller chunks may cause an inefficient read-modify-rewrite.
python.library.os#os.stat_result.st_blksize
st_blocks Number of 512-byte blocks allocated for file. This may be smaller than st_size/512 when the file has holes.
python.library.os#os.stat_result.st_blocks
st_creator Creator of the file.
python.library.os#os.stat_result.st_creator
st_ctime Platform dependent: the time of most recent metadata change on Unix, the time of creation on Windows, expressed in seconds.
python.library.os#os.stat_result.st_ctime
st_ctime_ns Platform dependent: the time of most recent metadata change on Unix, the time of creation on Windows, expressed in nanoseconds as an integer.
python.library.os#os.stat_result.st_ctime_ns
st_dev Identifier of the device on which this file resides.
python.library.os#os.stat_result.st_dev
st_file_attributes Windows file attributes: dwFileAttributes member of the BY_HANDLE_FILE_INFORMATION structure returned by GetFileInformationByHandle(). See the FILE_ATTRIBUTE_* constants in the stat module.
python.library.os#os.stat_result.st_file_attributes
st_flags User defined flags for file.
python.library.os#os.stat_result.st_flags
st_fstype String that uniquely identifies the type of the filesystem that contains the file.
python.library.os#os.stat_result.st_fstype
st_gen File generation number.
python.library.os#os.stat_result.st_gen
st_gid Group identifier of the file owner.
python.library.os#os.stat_result.st_gid
st_ino Platform dependent, but if non-zero, uniquely identifies the file for a given value of st_dev. Typically: the inode number on Unix, the file index on Windows
python.library.os#os.stat_result.st_ino
st_mode File mode: file type and file mode bits (permissions).
python.library.os#os.stat_result.st_mode
st_mtime Time of most recent content modification expressed in seconds.
python.library.os#os.stat_result.st_mtime
st_mtime_ns Time of most recent content modification expressed in nanoseconds as an integer.
python.library.os#os.stat_result.st_mtime_ns
st_nlink Number of hard links.
python.library.os#os.stat_result.st_nlink
st_rdev Type of device if an inode device.
python.library.os#os.stat_result.st_rdev
st_reparse_tag When st_file_attributes has the FILE_ATTRIBUTE_REPARSE_POINT set, this field contains the tag identifying the type of reparse point. See the IO_REPARSE_TAG_* constants in the stat module.
python.library.os#os.stat_result.st_reparse_tag
st_rsize Real size of the file.
python.library.os#os.stat_result.st_rsize
st_size Size of the file in bytes, if it is a regular file or a symbolic link. The size of a symbolic link is the length of the pathname it contains, without a terminating null byte.
python.library.os#os.stat_result.st_size
st_type File type.
python.library.os#os.stat_result.st_type
st_uid User identifier of the file owner.
python.library.os#os.stat_result.st_uid
os.strerror(code) Return the error message corresponding to the error code in code. On platforms where strerror() returns NULL when given an unknown error number, ValueError is raised.
python.library.os#os.strerror
os.supports_bytes_environ True if the native OS type of the environment is bytes (eg. False on Windows). New in version 3.2.
python.library.os#os.supports_bytes_environ
os.supports_dir_fd A set object indicating which functions in the os module accept an open file descriptor for their dir_fd parameter. Different platforms provide different features, and the underlying functionality Python uses to implement the dir_fd parameter is not available on all platforms Python supports. For consistency’s sake, functions that may support dir_fd always allow specifying the parameter, but will throw an exception if the functionality is used when it’s not locally available. (Specifying None for dir_fd is always supported on all platforms.) To check whether a particular function accepts an open file descriptor for its dir_fd parameter, use the in operator on supports_dir_fd. As an example, this expression evaluates to True if os.stat() accepts open file descriptors for dir_fd on the local platform: os.stat in os.supports_dir_fd Currently dir_fd parameters only work on Unix platforms; none of them work on Windows. New in version 3.3.
python.library.os#os.supports_dir_fd
os.supports_effective_ids A set object indicating whether os.access() permits specifying True for its effective_ids parameter on the local platform. (Specifying False for effective_ids is always supported on all platforms.) If the local platform supports it, the collection will contain os.access(); otherwise it will be empty. This expression evaluates to True if os.access() supports effective_ids=True on the local platform: os.access in os.supports_effective_ids Currently effective_ids is only supported on Unix platforms; it does not work on Windows. New in version 3.3.
python.library.os#os.supports_effective_ids
os.supports_fd A set object indicating which functions in the os module permit specifying their path parameter as an open file descriptor on the local platform. Different platforms provide different features, and the underlying functionality Python uses to accept open file descriptors as path arguments is not available on all platforms Python supports. To determine whether a particular function permits specifying an open file descriptor for its path parameter, use the in operator on supports_fd. As an example, this expression evaluates to True if os.chdir() accepts open file descriptors for path on your local platform: os.chdir in os.supports_fd New in version 3.3.
python.library.os#os.supports_fd
os.supports_follow_symlinks A set object indicating which functions in the os module accept False for their follow_symlinks parameter on the local platform. Different platforms provide different features, and the underlying functionality Python uses to implement follow_symlinks is not available on all platforms Python supports. For consistency’s sake, functions that may support follow_symlinks always allow specifying the parameter, but will throw an exception if the functionality is used when it’s not locally available. (Specifying True for follow_symlinks is always supported on all platforms.) To check whether a particular function accepts False for its follow_symlinks parameter, use the in operator on supports_follow_symlinks. As an example, this expression evaluates to True if you may specify follow_symlinks=False when calling os.stat() on the local platform: os.stat in os.supports_follow_symlinks New in version 3.3.
python.library.os#os.supports_follow_symlinks
os.symlink(src, dst, target_is_directory=False, *, dir_fd=None) Create a symbolic link pointing to src named dst. On Windows, a symlink represents either a file or a directory, and does not morph to the target dynamically. If the target is present, the type of the symlink will be created to match. Otherwise, the symlink will be created as a directory if target_is_directory is True or a file symlink (the default) otherwise. On non-Windows platforms, target_is_directory is ignored. This function can support paths relative to directory descriptors. Note On newer versions of Windows 10, unprivileged accounts can create symlinks if Developer Mode is enabled. When Developer Mode is not available/enabled, the SeCreateSymbolicLinkPrivilege privilege is required, or the process must be run as an administrator. OSError is raised when the function is called by an unprivileged user. Raises an auditing event os.symlink with arguments src, dst, dir_fd. Availability: Unix, Windows. Changed in version 3.2: Added support for Windows 6.0 (Vista) symbolic links. New in version 3.3: Added the dir_fd argument, and now allow target_is_directory on non-Windows platforms. Changed in version 3.6: Accepts a path-like object for src and dst. Changed in version 3.8: Added support for unelevated symlinks on Windows with Developer Mode.
python.library.os#os.symlink
os.sync() Force write of everything to disk. Availability: Unix. New in version 3.3.
python.library.os#os.sync
os.sysconf(name) Return integer-valued system configuration values. If the configuration value specified by name isn’t defined, -1 is returned. The comments regarding the name parameter for confstr() apply here as well; the dictionary that provides information on the known names is given by sysconf_names. Availability: Unix.
python.library.os#os.sysconf
os.sysconf_names Dictionary mapping names accepted by sysconf() to the integer values defined for those names by the host operating system. This can be used to determine the set of names known to the system. Availability: Unix.
python.library.os#os.sysconf_names
os.system(command) Execute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations. Changes to sys.stdin, etc. are not reflected in the environment of the executed command. If command generates any output, it will be sent to the interpreter standard output stream. On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent. On Windows, the return value is that returned by the system shell after running command. The shell is given by the Windows environment variable COMSPEC: it is usually cmd.exe, which returns the exit status of the command run; on systems using a non-native shell, consult your shell documentation. The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes. On Unix, waitstatus_to_exitcode() can be used to convert the result (exit status) into an exit code. On Windows, the result is directly the exit code. Raises an auditing event os.system with argument command. Availability: Unix, Windows.
python.library.os#os.system
os.tcgetpgrp(fd) Return the process group associated with the terminal given by fd (an open file descriptor as returned by os.open()). Availability: Unix.
python.library.os#os.tcgetpgrp
os.tcsetpgrp(fd, pg) Set the process group associated with the terminal given by fd (an open file descriptor as returned by os.open()) to pg. Availability: Unix.
python.library.os#os.tcsetpgrp
class os.terminal_size A subclass of tuple, holding (columns, lines) of the terminal window size. columns Width of the terminal window in characters. lines Height of the terminal window in characters.
python.library.os#os.terminal_size
columns Width of the terminal window in characters.
python.library.os#os.terminal_size.columns
lines Height of the terminal window in characters.
python.library.os#os.terminal_size.lines
os.times() Returns the current global process times. The return value is an object with five attributes: user - user time system - system time children_user - user time of all child processes children_system - system time of all child processes elapsed - elapsed real time since a fixed point in the past For backwards compatibility, this object also behaves like a five-tuple containing user, system, children_user, children_system, and elapsed in that order. See the Unix manual page times(2) and times(3) manual page on Unix or the GetProcessTimes MSDN on Windows. On Windows, only user and system are known; the other attributes are zero. Availability: Unix, Windows. Changed in version 3.3: Return type changed from a tuple to a tuple-like object with named attributes.
python.library.os#os.times
os.truncate(path, length) Truncate the file corresponding to path, so that it is at most length bytes in size. This function can support specifying a file descriptor. Raises an auditing event os.truncate with arguments path, length. Availability: Unix, Windows. New in version 3.3. Changed in version 3.5: Added support for Windows Changed in version 3.6: Accepts a path-like object.
python.library.os#os.truncate
os.ttyname(fd) Return a string which specifies the terminal device associated with file descriptor fd. If fd is not associated with a terminal device, an exception is raised. Availability: Unix.
python.library.os#os.ttyname
os.umask(mask) Set the current numeric umask and return the previous umask.
python.library.os#os.umask
os.uname() Returns information identifying the current operating system. The return value is an object with five attributes: sysname - operating system name nodename - name of machine on network (implementation-defined) release - operating system release version - operating system version machine - hardware identifier For backwards compatibility, this object is also iterable, behaving like a five-tuple containing sysname, nodename, release, version, and machine in that order. Some systems truncate nodename to 8 characters or to the leading component; a better way to get the hostname is socket.gethostname() or even socket.gethostbyaddr(socket.gethostname()). Availability: recent flavors of Unix. Changed in version 3.3: Return type changed from a tuple to a tuple-like object with named attributes.
python.library.os#os.uname
os.unlink(path, *, dir_fd=None) Remove (delete) the file path. This function is semantically identical to remove(); the unlink name is its traditional Unix name. Please see the documentation for remove() for further information. Raises an auditing event os.remove with arguments path, dir_fd. New in version 3.3: The dir_fd parameter. Changed in version 3.6: Accepts a path-like object.
python.library.os#os.unlink
os.unsetenv(key) Unset (delete) the environment variable named key. Such changes to the environment affect subprocesses started with os.system(), popen() or fork() and execv(). Deletion of items in os.environ is automatically translated into a corresponding call to unsetenv(); however, calls to unsetenv() don’t update os.environ, so it is actually preferable to delete items of os.environ. Raises an auditing event os.unsetenv with argument key. Changed in version 3.9: The function is now always available and is also available on Windows.
python.library.os#os.unsetenv
os.urandom(size) Return a string of size random bytes suitable for cryptographic use. This function returns random bytes from an OS-specific randomness source. The returned data should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation. On Linux, if the getrandom() syscall is available, it is used in blocking mode: block until the system urandom entropy pool is initialized (128 bits of entropy are collected by the kernel). See the PEP 524 for the rationale. On Linux, the getrandom() function can be used to get random bytes in non-blocking mode (using the GRND_NONBLOCK flag) or to poll until the system urandom entropy pool is initialized. On a Unix-like system, random bytes are read from the /dev/urandom device. If the /dev/urandom device is not available or not readable, the NotImplementedError exception is raised. On Windows, it will use CryptGenRandom(). See also The secrets module provides higher level functions. For an easy-to-use interface to the random number generator provided by your platform, please see random.SystemRandom. Changed in version 3.6.0: On Linux, getrandom() is now used in blocking mode to increase the security. Changed in version 3.5.2: On Linux, if the getrandom() syscall blocks (the urandom entropy pool is not initialized yet), fall back on reading /dev/urandom. Changed in version 3.5: On Linux 3.17 and newer, the getrandom() syscall is now used when available. On OpenBSD 5.6 and newer, the C getentropy() function is now used. These functions avoid the usage of an internal file descriptor.
python.library.os#os.urandom
os.utime(path, times=None, *, [ns, ]dir_fd=None, follow_symlinks=True) Set the access and modified times of the file specified by path. utime() takes two optional parameters, times and ns. These specify the times set on path and are used as follows: If ns is specified, it must be a 2-tuple of the form (atime_ns, mtime_ns) where each member is an int expressing nanoseconds. If times is not None, it must be a 2-tuple of the form (atime, mtime) where each member is an int or float expressing seconds. If times is None and ns is unspecified, this is equivalent to specifying ns=(atime_ns, mtime_ns) where both times are the current time. It is an error to specify tuples for both times and ns. Note that the exact times you set here may not be returned by a subsequent stat() call, depending on the resolution with which your operating system records access and modification times; see stat(). The best way to preserve exact times is to use the st_atime_ns and st_mtime_ns fields from the os.stat() result object with the ns parameter to utime. This function can support specifying a file descriptor, paths relative to directory descriptors and not following symlinks. Raises an auditing event os.utime with arguments path, times, ns, dir_fd. New in version 3.3: Added support for specifying path as an open file descriptor, and the dir_fd, follow_symlinks, and ns parameters. Changed in version 3.6: Accepts a path-like object.
python.library.os#os.utime
os.wait() Wait for completion of a child process, and return a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced. waitstatus_to_exitcode() can be used to convert the exit status into an exit code. Availability: Unix. See also waitpid() can be used to wait for the completion of a specific child process and has more options.
python.library.os#os.wait
os.wait3(options) Similar to waitpid(), except no process id argument is given and a 3-element tuple containing the child’s process id, exit status indication, and resource usage information is returned. Refer to resource.getrusage() for details on resource usage information. The option argument is the same as that provided to waitpid() and wait4(). waitstatus_to_exitcode() can be used to convert the exit status into an exitcode. Availability: Unix.
python.library.os#os.wait3
os.wait4(pid, options) Similar to waitpid(), except a 3-element tuple, containing the child’s process id, exit status indication, and resource usage information is returned. Refer to resource.getrusage() for details on resource usage information. The arguments to wait4() are the same as those provided to waitpid(). waitstatus_to_exitcode() can be used to convert the exit status into an exitcode. Availability: Unix.
python.library.os#os.wait4
os.waitid(idtype, id, options) Wait for the completion of one or more child processes. idtype can be P_PID, P_PGID, P_ALL, or P_PIDFD on Linux. id specifies the pid to wait on. options is constructed from the ORing of one or more of WEXITED, WSTOPPED or WCONTINUED and additionally may be ORed with WNOHANG or WNOWAIT. The return value is an object representing the data contained in the siginfo_t structure, namely: si_pid, si_uid, si_signo, si_status, si_code or None if WNOHANG is specified and there are no children in a waitable state. Availability: Unix. New in version 3.3.
python.library.os#os.waitid
os.waitpid(pid, options) The details of this function differ on Unix and Windows. On Unix: Wait for completion of a child process given by process id pid, and return a tuple containing its process id and exit status indication (encoded as for wait()). The semantics of the call are affected by the value of the integer options, which should be 0 for normal operation. If pid is greater than 0, waitpid() requests status information for that specific process. If pid is 0, the request is for the status of any child in the process group of the current process. If pid is -1, the request pertains to any child of the current process. If pid is less than -1, status is requested for any process in the process group -pid (the absolute value of pid). An OSError is raised with the value of errno when the syscall returns -1. On Windows: Wait for completion of a process given by process handle pid, and return a tuple containing pid, and its exit status shifted left by 8 bits (shifting makes cross-platform use of the function easier). A pid less than or equal to 0 has no special meaning on Windows, and raises an exception. The value of integer options has no effect. pid can refer to any process whose id is known, not necessarily a child process. The spawn* functions called with P_NOWAIT return suitable process handles. waitstatus_to_exitcode() can be used to convert the exit status into an exit code. Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).
python.library.os#os.waitpid
os.waitstatus_to_exitcode(status) Convert a wait status to an exit code. On Unix: If the process exited normally (if WIFEXITED(status) is true), return the process exit status (return WEXITSTATUS(status)): result greater than or equal to 0. If the process was terminated by a signal (if WIFSIGNALED(status) is true), return -signum where signum is the number of the signal that caused the process to terminate (return -WTERMSIG(status)): result less than 0. Otherwise, raise a ValueError. On Windows, return status shifted right by 8 bits. On Unix, if the process is being traced or if waitpid() was called with WUNTRACED option, the caller must first check if WIFSTOPPED(status) is true. This function must not be called if WIFSTOPPED(status) is true. See also WIFEXITED(), WEXITSTATUS(), WIFSIGNALED(), WTERMSIG(), WIFSTOPPED(), WSTOPSIG() functions. New in version 3.9.
python.library.os#os.waitstatus_to_exitcode
os.walk(top, topdown=True, onerror=None, followlinks=False) Generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames). dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists contain no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name). Whether or not the lists are sorted depends on the file system. If a file is removed from or added to the dirpath directory during generating the lists, whether a name for that file be included is unspecified. If optional argument topdown is True or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top-down). If topdown is False, the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom-up). No matter the value of topdown, the list of subdirectories is retrieved before the tuples for the directory and its subdirectories are generated. When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific order of visiting, or even to inform walk() about directories the caller creates or renames before it resumes walk() again. Modifying dirnames when topdown is False has no effect on the behavior of the walk, because in bottom-up mode the directories in dirnames are generated before dirpath itself is generated. By default, errors from the scandir() call are ignored. If optional argument onerror is specified, it should be a function; it will be called with one argument, an OSError instance. It can report the error to continue with the walk, or raise the exception to abort the walk. Note that the filename is available as the filename attribute of the exception object. By default, walk() will not walk down into symbolic links that resolve to directories. Set followlinks to True to visit directories pointed to by symlinks, on systems that support them. Note Be aware that setting followlinks to True can lead to infinite recursion if a link points to a parent directory of itself. walk() does not keep track of the directories it visited already. Note If you pass a relative pathname, don’t change the current working directory between resumptions of walk(). walk() never changes the current directory, and assumes that its caller doesn’t either. This example displays the number of bytes taken by non-directory files in each directory under the starting directory, except that it doesn’t look under any CVS subdirectory: import os from os.path import join, getsize for root, dirs, files in os.walk('python/Lib/email'): print(root, "consumes", end=" ") print(sum(getsize(join(root, name)) for name in files), end=" ") print("bytes in", len(files), "non-directory files") if 'CVS' in dirs: dirs.remove('CVS') # don't visit CVS directories In the next example (simple implementation of shutil.rmtree()), walking the tree bottom-up is essential, rmdir() doesn’t allow deleting a directory before the directory is empty: # Delete everything reachable from the directory named in "top", # assuming there are no symbolic links. # CAUTION: This is dangerous! For example, if top == '/', it # could delete all your disk files. import os for root, dirs, files in os.walk(top, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name)) Raises an auditing event os.walk with arguments top, topdown, onerror, followlinks. Changed in version 3.5: This function now calls os.scandir() instead of os.listdir(), making it faster by reducing the number of calls to os.stat(). Changed in version 3.6: Accepts a path-like object.
python.library.os#os.walk
os.WCONTINUED This option causes child processes to be reported if they have been continued from a job control stop since their status was last reported. Availability: some Unix systems.
python.library.os#os.WCONTINUED
os.WCOREDUMP(status) Return True if a core dump was generated for the process, otherwise return False. This function should be employed only if WIFSIGNALED() is true. Availability: Unix.
python.library.os#os.WCOREDUMP
os.WEXITED os.WSTOPPED os.WNOWAIT Flags that can be used in options in waitid() that specify what child signal to wait for. Availability: Unix. New in version 3.3.
python.library.os#os.WEXITED
os.WEXITSTATUS(status) Return the process exit status. This function should be employed only if WIFEXITED() is true. Availability: Unix.
python.library.os#os.WEXITSTATUS
os.WIFCONTINUED(status) Return True if a stopped child has been resumed by delivery of SIGCONT (if the process has been continued from a job control stop), otherwise return False. See WCONTINUED option. Availability: Unix.
python.library.os#os.WIFCONTINUED
os.WIFEXITED(status) Return True if the process exited terminated normally, that is, by calling exit() or _exit(), or by returning from main(); otherwise return False. Availability: Unix.
python.library.os#os.WIFEXITED
os.WIFSIGNALED(status) Return True if the process was terminated by a signal, otherwise return False. Availability: Unix.
python.library.os#os.WIFSIGNALED
os.WIFSTOPPED(status) Return True if the process was stopped by delivery of a signal, otherwise return False. WIFSTOPPED() only returns True if the waitpid() call was done using WUNTRACED option or when the process is being traced (see ptrace(2)). Availability: Unix.
python.library.os#os.WIFSTOPPED
os.WNOHANG The option for waitpid() to return immediately if no child process status is available immediately. The function returns (0, 0) in this case. Availability: Unix.
python.library.os#os.WNOHANG
os.WEXITED os.WSTOPPED os.WNOWAIT Flags that can be used in options in waitid() that specify what child signal to wait for. Availability: Unix. New in version 3.3.
python.library.os#os.WNOWAIT
os.write(fd, str) Write the bytestring in str to file descriptor fd. Return the number of bytes actually written. Note This function is intended for low-level I/O and must be applied to a file descriptor as returned by os.open() or pipe(). To write a “file object” returned by the built-in function open() or by popen() or fdopen(), or sys.stdout or sys.stderr, use its write() method. Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).
python.library.os#os.write
os.writev(fd, buffers) Write the contents of buffers to file descriptor fd. buffers must be a sequence of bytes-like objects. Buffers are processed in array order. Entire contents of the first buffer is written before proceeding to the second, and so on. Returns the total number of bytes actually written. The operating system may set a limit (sysconf() value 'SC_IOV_MAX') on the number of buffers that can be used. Availability: Unix. New in version 3.3.
python.library.os#os.writev
os.WEXITED os.WSTOPPED os.WNOWAIT Flags that can be used in options in waitid() that specify what child signal to wait for. Availability: Unix. New in version 3.3.
python.library.os#os.WSTOPPED
os.WSTOPSIG(status) Return the signal which caused the process to stop. This function should be employed only if WIFSTOPPED() is true. Availability: Unix.
python.library.os#os.WSTOPSIG
os.WTERMSIG(status) Return the number of the signal that caused the process to terminate. This function should be employed only if WIFSIGNALED() is true. Availability: Unix.
python.library.os#os.WTERMSIG
os.WUNTRACED This option causes child processes to be reported if they have been stopped but their current state has not been reported since they were stopped. Availability: Unix.
python.library.os#os.WUNTRACED
os.F_OK os.R_OK os.W_OK os.X_OK Values to pass as the mode parameter of access() to test the existence, readability, writability and executability of path, respectively.
python.library.os#os.W_OK
os.XATTR_CREATE This is a possible value for the flags argument in setxattr(). It indicates the operation must create an attribute.
python.library.os#os.XATTR_CREATE
os.XATTR_REPLACE This is a possible value for the flags argument in setxattr(). It indicates the operation must replace an existing attribute.
python.library.os#os.XATTR_REPLACE
os.XATTR_SIZE_MAX The maximum size the value of an extended attribute can be. Currently, this is 64 KiB on Linux.
python.library.os#os.XATTR_SIZE_MAX
os.F_OK os.R_OK os.W_OK os.X_OK Values to pass as the mode parameter of access() to test the existence, readability, writability and executability of path, respectively.
python.library.os#os.X_OK
os._exit(n) Exit the process with status n, without calling cleanup handlers, flushing stdio buffers, etc. Note The standard way to exit is sys.exit(n). _exit() should normally only be used in the child process after a fork().
python.library.os#os._exit
exception OSError([arg]) exception OSError(errno, strerror[, filename[, winerror[, filename2]]]) This exception is raised when a system function returns a system-related error, including I/O failures such as “file not found” or “disk full” (not for illegal argument types or other incidental errors). The second form of the constructor sets the corresponding attributes, described below. The attributes default to None if not specified. For backwards compatibility, if three arguments are passed, the args attribute contains only a 2-tuple of the first two constructor arguments. The constructor often actually returns a subclass of OSError, as described in OS exceptions below. The particular subclass depends on the final errno value. This behaviour only occurs when constructing OSError directly or via an alias, and is not inherited when subclassing. errno A numeric error code from the C variable errno. winerror Under Windows, this gives you the native Windows error code. The errno attribute is then an approximate translation, in POSIX terms, of that native error code. Under Windows, if the winerror constructor argument is an integer, the errno attribute is determined from the Windows error code, and the errno argument is ignored. On other platforms, the winerror argument is ignored, and the winerror attribute does not exist. strerror The corresponding error message, as provided by the operating system. It is formatted by the C functions perror() under POSIX, and FormatMessage() under Windows. filename filename2 For exceptions that involve a file system path (such as open() or os.unlink()), filename is the file name passed to the function. For functions that involve two file system paths (such as os.rename()), filename2 corresponds to the second file name passed to the function. Changed in version 3.3: EnvironmentError, IOError, WindowsError, socket.error, select.error and mmap.error have been merged into OSError, and the constructor may return a subclass. Changed in version 3.4: The filename attribute is now the original file name passed to the function, instead of the name encoded to or decoded from the filesystem encoding. Also, the filename2 constructor argument and attribute was added.
python.library.exceptions#OSError
errno A numeric error code from the C variable errno.
python.library.exceptions#OSError.errno
filename filename2 For exceptions that involve a file system path (such as open() or os.unlink()), filename is the file name passed to the function. For functions that involve two file system paths (such as os.rename()), filename2 corresponds to the second file name passed to the function.
python.library.exceptions#OSError.filename
filename filename2 For exceptions that involve a file system path (such as open() or os.unlink()), filename is the file name passed to the function. For functions that involve two file system paths (such as os.rename()), filename2 corresponds to the second file name passed to the function.
python.library.exceptions#OSError.filename2
strerror The corresponding error message, as provided by the operating system. It is formatted by the C functions perror() under POSIX, and FormatMessage() under Windows.
python.library.exceptions#OSError.strerror
winerror Under Windows, this gives you the native Windows error code. The errno attribute is then an approximate translation, in POSIX terms, of that native error code. Under Windows, if the winerror constructor argument is an integer, the errno attribute is determined from the Windows error code, and the errno argument is ignored. On other platforms, the winerror argument is ignored, and the winerror attribute does not exist.
python.library.exceptions#OSError.winerror
ossaudiodev — Access to OSS-compatible audio devices This module allows you to access the OSS (Open Sound System) audio interface. OSS is available for a wide range of open-source and commercial Unices, and is the standard audio interface for Linux and recent versions of FreeBSD. Changed in version 3.3: Operations in this module now raise OSError where IOError was raised. See also Open Sound System Programmer’s Guide the official documentation for the OSS C API The module defines a large number of constants supplied by the OSS device driver; see <sys/soundcard.h> on either Linux or FreeBSD for a listing. ossaudiodev defines the following variables and functions: exception ossaudiodev.OSSAudioError This exception is raised on certain errors. The argument is a string describing what went wrong. (If ossaudiodev receives an error from a system call such as open(), write(), or ioctl(), it raises OSError. Errors detected directly by ossaudiodev result in OSSAudioError.) (For backwards compatibility, the exception class is also available as ossaudiodev.error.) ossaudiodev.open(mode) ossaudiodev.open(device, mode) Open an audio device and return an OSS audio device object. This object supports many file-like methods, such as read(), write(), and fileno() (although there are subtle differences between conventional Unix read/write semantics and those of OSS audio devices). It also supports a number of audio-specific methods; see below for the complete list of methods. device is the audio device filename to use. If it is not specified, this module first looks in the environment variable AUDIODEV for a device to use. If not found, it falls back to /dev/dsp. mode is one of 'r' for read-only (record) access, 'w' for write-only (playback) access and 'rw' for both. Since many sound cards only allow one process to have the recorder or player open at a time, it is a good idea to open the device only for the activity needed. Further, some sound cards are half-duplex: they can be opened for reading or writing, but not both at once. Note the unusual calling syntax: the first argument is optional, and the second is required. This is a historical artifact for compatibility with the older linuxaudiodev module which ossaudiodev supersedes. ossaudiodev.openmixer([device]) Open a mixer device and return an OSS mixer device object. device is the mixer device filename to use. If it is not specified, this module first looks in the environment variable MIXERDEV for a device to use. If not found, it falls back to /dev/mixer. Audio Device Objects Before you can write to or read from an audio device, you must call three methods in the correct order: setfmt() to set the output format channels() to set the number of channels speed() to set the sample rate Alternately, you can use the setparameters() method to set all three audio parameters at once. This is more convenient, but may not be as flexible in all cases. The audio device objects returned by open() define the following methods and (read-only) attributes: oss_audio_device.close() Explicitly close the audio device. When you are done writing to or reading from an audio device, you should explicitly close it. A closed device cannot be used again. oss_audio_device.fileno() Return the file descriptor associated with the device. oss_audio_device.read(size) Read size bytes from the audio input and return them as a Python string. Unlike most Unix device drivers, OSS audio devices in blocking mode (the default) will block read() until the entire requested amount of data is available. oss_audio_device.write(data) Write a bytes-like object data to the audio device and return the number of bytes written. If the audio device is in blocking mode (the default), the entire data is always written (again, this is different from usual Unix device semantics). If the device is in non-blocking mode, some data may not be written—see writeall(). Changed in version 3.5: Writable bytes-like object is now accepted. oss_audio_device.writeall(data) Write a bytes-like object data to the audio device: waits until the audio device is able to accept data, writes as much data as it will accept, and repeats until data has been completely written. If the device is in blocking mode (the default), this has the same effect as write(); writeall() is only useful in non-blocking mode. Has no return value, since the amount of data written is always equal to the amount of data supplied. Changed in version 3.5: Writable bytes-like object is now accepted. Changed in version 3.2: Audio device objects also support the context management protocol, i.e. they can be used in a with statement. The following methods each map to exactly one ioctl() system call. The correspondence is obvious: for example, setfmt() corresponds to the SNDCTL_DSP_SETFMT ioctl, and sync() to SNDCTL_DSP_SYNC (this can be useful when consulting the OSS documentation). If the underlying ioctl() fails, they all raise OSError. oss_audio_device.nonblock() Put the device into non-blocking mode. Once in non-blocking mode, there is no way to return it to blocking mode. oss_audio_device.getfmts() Return a bitmask of the audio output formats supported by the soundcard. Some of the formats supported by OSS are: Format Description AFMT_MU_LAW a logarithmic encoding (used by Sun .au files and /dev/audio) AFMT_A_LAW a logarithmic encoding AFMT_IMA_ADPCM a 4:1 compressed format defined by the Interactive Multimedia Association AFMT_U8 Unsigned, 8-bit audio AFMT_S16_LE Signed, 16-bit audio, little-endian byte order (as used by Intel processors) AFMT_S16_BE Signed, 16-bit audio, big-endian byte order (as used by 68k, PowerPC, Sparc) AFMT_S8 Signed, 8 bit audio AFMT_U16_LE Unsigned, 16-bit little-endian audio AFMT_U16_BE Unsigned, 16-bit big-endian audio Consult the OSS documentation for a full list of audio formats, and note that most devices support only a subset of these formats. Some older devices only support AFMT_U8; the most common format used today is AFMT_S16_LE. oss_audio_device.setfmt(format) Try to set the current audio format to format—see getfmts() for a list. Returns the audio format that the device was set to, which may not be the requested format. May also be used to return the current audio format—do this by passing an “audio format” of AFMT_QUERY. oss_audio_device.channels(nchannels) Set the number of output channels to nchannels. A value of 1 indicates monophonic sound, 2 stereophonic. Some devices may have more than 2 channels, and some high-end devices may not support mono. Returns the number of channels the device was set to. oss_audio_device.speed(samplerate) Try to set the audio sampling rate to samplerate samples per second. Returns the rate actually set. Most sound devices don’t support arbitrary sampling rates. Common rates are: Rate Description 8000 default rate for /dev/audio 11025 speech recording 22050 44100 CD quality audio (at 16 bits/sample and 2 channels) 96000 DVD quality audio (at 24 bits/sample) oss_audio_device.sync() Wait until the sound device has played every byte in its buffer. (This happens implicitly when the device is closed.) The OSS documentation recommends closing and re-opening the device rather than using sync(). oss_audio_device.reset() Immediately stop playing or recording and return the device to a state where it can accept commands. The OSS documentation recommends closing and re-opening the device after calling reset(). oss_audio_device.post() Tell the driver that there is likely to be a pause in the output, making it possible for the device to handle the pause more intelligently. You might use this after playing a spot sound effect, before waiting for user input, or before doing disk I/O. The following convenience methods combine several ioctls, or one ioctl and some simple calculations. oss_audio_device.setparameters(format, nchannels, samplerate[, strict=False]) Set the key audio sampling parameters—sample format, number of channels, and sampling rate—in one method call. format, nchannels, and samplerate should be as specified in the setfmt(), channels(), and speed() methods. If strict is true, setparameters() checks to see if each parameter was actually set to the requested value, and raises OSSAudioError if not. Returns a tuple (format, nchannels, samplerate) indicating the parameter values that were actually set by the device driver (i.e., the same as the return values of setfmt(), channels(), and speed()). For example, (fmt, channels, rate) = dsp.setparameters(fmt, channels, rate) is equivalent to fmt = dsp.setfmt(fmt) channels = dsp.channels(channels) rate = dsp.rate(rate) oss_audio_device.bufsize() Returns the size of the hardware buffer, in samples. oss_audio_device.obufcount() Returns the number of samples that are in the hardware buffer yet to be played. oss_audio_device.obuffree() Returns the number of samples that could be queued into the hardware buffer to be played without blocking. Audio device objects also support several read-only attributes: oss_audio_device.closed Boolean indicating whether the device has been closed. oss_audio_device.name String containing the name of the device file. oss_audio_device.mode The I/O mode for the file, either "r", "rw", or "w". Mixer Device Objects The mixer object provides two file-like methods: oss_mixer_device.close() This method closes the open mixer device file. Any further attempts to use the mixer after this file is closed will raise an OSError. oss_mixer_device.fileno() Returns the file handle number of the open mixer device file. Changed in version 3.2: Mixer objects also support the context management protocol. The remaining methods are specific to audio mixing: oss_mixer_device.controls() This method returns a bitmask specifying the available mixer controls (“Control” being a specific mixable “channel”, such as SOUND_MIXER_PCM or SOUND_MIXER_SYNTH). This bitmask indicates a subset of all available mixer controls—the SOUND_MIXER_* constants defined at module level. To determine if, for example, the current mixer object supports a PCM mixer, use the following Python code: mixer=ossaudiodev.openmixer() if mixer.controls() & (1 << ossaudiodev.SOUND_MIXER_PCM): # PCM is supported ... code ... For most purposes, the SOUND_MIXER_VOLUME (master volume) and SOUND_MIXER_PCM controls should suffice—but code that uses the mixer should be flexible when it comes to choosing mixer controls. On the Gravis Ultrasound, for example, SOUND_MIXER_VOLUME does not exist. oss_mixer_device.stereocontrols() Returns a bitmask indicating stereo mixer controls. If a bit is set, the corresponding control is stereo; if it is unset, the control is either monophonic or not supported by the mixer (use in combination with controls() to determine which). See the code example for the controls() function for an example of getting data from a bitmask. oss_mixer_device.reccontrols() Returns a bitmask specifying the mixer controls that may be used to record. See the code example for controls() for an example of reading from a bitmask. oss_mixer_device.get(control) Returns the volume of a given mixer control. The returned volume is a 2-tuple (left_volume,right_volume). Volumes are specified as numbers from 0 (silent) to 100 (full volume). If the control is monophonic, a 2-tuple is still returned, but both volumes are the same. Raises OSSAudioError if an invalid control is specified, or OSError if an unsupported control is specified. oss_mixer_device.set(control, (left, right)) Sets the volume for a given mixer control to (left,right). left and right must be ints and between 0 (silent) and 100 (full volume). On success, the new volume is returned as a 2-tuple. Note that this may not be exactly the same as the volume specified, because of the limited resolution of some soundcard’s mixers. Raises OSSAudioError if an invalid mixer control was specified, or if the specified volumes were out-of-range. oss_mixer_device.get_recsrc() This method returns a bitmask indicating which control(s) are currently being used as a recording source. oss_mixer_device.set_recsrc(bitmask) Call this function to specify a recording source. Returns a bitmask indicating the new recording source (or sources) if successful; raises OSError if an invalid source was specified. To set the current recording source to the microphone input: mixer.setrecsrc (1 << ossaudiodev.SOUND_MIXER_MIC)
python.library.ossaudiodev
ossaudiodev.open(mode) ossaudiodev.open(device, mode) Open an audio device and return an OSS audio device object. This object supports many file-like methods, such as read(), write(), and fileno() (although there are subtle differences between conventional Unix read/write semantics and those of OSS audio devices). It also supports a number of audio-specific methods; see below for the complete list of methods. device is the audio device filename to use. If it is not specified, this module first looks in the environment variable AUDIODEV for a device to use. If not found, it falls back to /dev/dsp. mode is one of 'r' for read-only (record) access, 'w' for write-only (playback) access and 'rw' for both. Since many sound cards only allow one process to have the recorder or player open at a time, it is a good idea to open the device only for the activity needed. Further, some sound cards are half-duplex: they can be opened for reading or writing, but not both at once. Note the unusual calling syntax: the first argument is optional, and the second is required. This is a historical artifact for compatibility with the older linuxaudiodev module which ossaudiodev supersedes.
python.library.ossaudiodev#ossaudiodev.open
ossaudiodev.openmixer([device]) Open a mixer device and return an OSS mixer device object. device is the mixer device filename to use. If it is not specified, this module first looks in the environment variable MIXERDEV for a device to use. If not found, it falls back to /dev/mixer.
python.library.ossaudiodev#ossaudiodev.openmixer
exception ossaudiodev.OSSAudioError This exception is raised on certain errors. The argument is a string describing what went wrong. (If ossaudiodev receives an error from a system call such as open(), write(), or ioctl(), it raises OSError. Errors detected directly by ossaudiodev result in OSSAudioError.) (For backwards compatibility, the exception class is also available as ossaudiodev.error.)
python.library.ossaudiodev#ossaudiodev.OSSAudioError
oss_audio_device.bufsize() Returns the size of the hardware buffer, in samples.
python.library.ossaudiodev#ossaudiodev.oss_audio_device.bufsize
oss_audio_device.channels(nchannels) Set the number of output channels to nchannels. A value of 1 indicates monophonic sound, 2 stereophonic. Some devices may have more than 2 channels, and some high-end devices may not support mono. Returns the number of channels the device was set to.
python.library.ossaudiodev#ossaudiodev.oss_audio_device.channels
oss_audio_device.close() Explicitly close the audio device. When you are done writing to or reading from an audio device, you should explicitly close it. A closed device cannot be used again.
python.library.ossaudiodev#ossaudiodev.oss_audio_device.close
oss_audio_device.closed Boolean indicating whether the device has been closed.
python.library.ossaudiodev#ossaudiodev.oss_audio_device.closed
oss_audio_device.fileno() Return the file descriptor associated with the device.
python.library.ossaudiodev#ossaudiodev.oss_audio_device.fileno