getopt
— C-style parser for command line options¶
Source code: Lib/getopt.py
Note
This module is considered feature complete. A more declarative and
extensible alternative to this API is provided in the optparse
module. Further functional enhancements for command line parameter
processing are provided either as third party modules on PyPI,
or else as features in the argparse
module.
This module helps scripts to parse the command line arguments in sys.argv
.
It supports the same conventions as the Unix getopt()
function (including
the special meanings of arguments of the form ‘-
’ and ‘--
‘). Long
options similar to those supported by GNU software may be used as well via an
optional third argument.
Users who are unfamiliar with the Unix getopt()
function should consider
using the argparse
module instead. Users who are familiar with the Unix
getopt()
function, but would like to get equivalent behavior while
writing less code and getting better help and error messages should consider
using the optparse
module. See Choosing an argument parsing library for
additional details.
This module provides two functions and an exception:
- getopt.getopt(args, shortopts, longopts=[])¶
Parses command line options and parameter list. args is the argument list to be parsed, without the leading reference to the running program. Typically, this means
sys.argv[1:]
. shortopts is the string of option letters that the script wants to recognize, with options that require an argument followed by a colon (':'
) and options that accept an optional argument followed by two colons ('::'
); i.e., the same format that Unixgetopt()
uses.Note
Unlike GNU
getopt()
, after a non-option argument, all further arguments are considered also non-options. This is similar to the way non-GNU Unix systems work.longopts, if specified, must be a list of strings with the names of the long options which should be supported. The leading
'--'
characters should not be included in the option name. Long options which require an argument should be followed by an equal sign ('='
). Long options which accept an optional argument should be followed by an equal sign and question mark ('=?'
). To accept only long options, shortopts should be an empty string. Long options on the command line can be recognized so long as they provide a prefix of the option name that matches exactly one of the accepted options. For example, if longopts is['foo', 'frob']
, the option--fo
will match as--foo
, but--f
will not match uniquely, soGetoptError
will be raised.The return value consists of two elements: the first is a list of
(option, value)
pairs; the second is the list of program arguments left after the option list was stripped (this is a trailing slice of args). Each option-and-value pair returned has the option as its first element, prefixed with a hyphen for short options (e.g.,'-x'
) or two hyphens for long options (e.g.,'--long-option'
), and the option argument as its second element, or an empty string if the option has no argument. The options occur in the list in the same order in which they were found, thus allowing multiple occurrences. Long and short options may be mixed.Changed in version 3.14: Optional arguments are supported.
- getopt.gnu_getopt(args, shortopts, longopts=[])¶
This function works like
getopt()
, except that GNU style scanning mode is used by default. This means that option and non-option arguments may be intermixed. Thegetopt()
function stops processing options as soon as a non-option argument is encountered.If the first character of the option string is
'+'
, or if the environment variablePOSIXLY_CORRECT
is set, then option processing stops as soon as a non-option argument is encountered.If the first character of the option string is
'-'
, non-option arguments that are followed by options are added to the list of option-and-value pairs as a pair that hasNone
as its first element and the list of non-option arguments as its second element. The second element of thegnu_getopt()
result is a list of program arguments after the last option.Changed in version 3.14: Support for returning intermixed options and non-option arguments in order.
- exception getopt.GetoptError¶
This is raised when an unrecognized option is found in the argument list or when an option requiring an argument is given none. The argument to the exception is a string indicating the cause of the error. For long options, an argument given to an option which does not require one will also cause this exception to be raised. The attributes
msg
andopt
give the error message and related option; if there is no specific option to which the exception relates,opt
is an empty string.
- exception getopt.error¶
Alias for
GetoptError
; for backward compatibility.
An example using only Unix style options:
>>> import getopt
>>> args = '-a -b -cfoo -d bar a1 a2'.split()
>>> args
['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'abc:d:')
>>> optlist
[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', 'bar')]
>>> args
['a1', 'a2']
Using long option names is equally easy:
>>> s = '--condition=foo --testing --output-file abc.def -x a1 a2'
>>> args = s.split()
>>> args
['--condition=foo', '--testing', '--output-file', 'abc.def', '-x', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'x', [
... 'condition=', 'output-file=', 'testing'])
>>> optlist
[('--condition', 'foo'), ('--testing', ''), ('--output-file', 'abc.def'), ('-x', '')]
>>> args
['a1', 'a2']
Optional arguments should be specified explicitly:
>>> s = '-Con -C --color=off --color a1 a2'
>>> args = s.split()
>>> args
['-Con', '-C', '--color=off', '--color', 'a1', 'a2']
>>> optlist, args = getopt.getopt(args, 'C::', ['color=?'])
>>> optlist
[('-C', 'on'), ('-C', ''), ('--color', 'off'), ('--color', '')]
>>> args
['a1', 'a2']
The order of options and non-option arguments can be preserved:
>>> s = 'a1 -x a2 a3 a4 --long a5 a6'
>>> args = s.split()
>>> args
['a1', '-x', 'a2', 'a3', 'a4', '--long', 'a5', 'a6']
>>> optlist, args = getopt.gnu_getopt(args, '-x:', ['long='])
>>> optlist
[(None, ['a1']), ('-x', 'a2'), (None, ['a3', 'a4']), ('--long', 'a5')]
>>> args
['a6']
In a script, typical usage is something like this:
import getopt, sys
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
except getopt.GetoptError as err:
# print help information and exit:
print(err) # will print something like "option -a not recognized"
usage()
sys.exit(2)
output = None
verbose = False
for o, a in opts:
if o == "-v":
verbose = True
elif o in ("-h", "--help"):
usage()
sys.exit()
elif o in ("-o", "--output"):
output = a
else:
assert False, "unhandled option"
process(args, output=output, verbose=verbose)
if __name__ == "__main__":
main()
Note that an equivalent command line interface could be produced with less code
and more informative help and error messages by using the optparse
module:
import optparse
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option('-o', '--output')
parser.add_option('-v', dest='verbose', action='store_true')
opts, args = parser.parse_args()
process(args, output=opts.output, verbose=opts.verbose)
A roughly equivalent command line interface for this case can also be
produced by using the argparse
module:
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--output')
parser.add_argument('-v', dest='verbose', action='store_true')
parser.add_argument('rest', nargs='*')
args = parser.parse_args()
process(args.rest, output=args.output, verbose=args.verbose)
See Choosing an argument parsing library for details on how the argparse
version of this code differs in behaviour from the optparse
(and
getopt
) version.


Superseded Modules

Superseded Modules¶
The modules described in this chapter have been superseded by other modules for most use cases, and are retained primarily to preserve backwards compatibility.
Modules may appear in this chapter because they only cover a limited subset of
a problem space, and a more generally applicable solution is available elsewhere
in the standard library (for example, getopt
covers the very specific
task of “mimic the C getopt()
API in Python”, rather than the broader
command line option parsing and argument parsing capabilities offered by
optparse
and argparse
).
Alternatively, modules may appear in this chapter because they are deprecated outright, and awaiting removal in a future release, or they are soft deprecated and their use is actively discouraged in new projects. With the removal of various obsolete modules through PEP 594, there are currently no modules in this latter category.


Modules command-line interface (CLI)

Modules command-line interface (CLI)¶
The following modules have a command-line interface.
encodings.rot_13
this
See also the Python command-line interface.
The following modules have a command-line interface.
encodings.rot_13
this
See also the Python command-line interface.


— Unix syslog library routines

syslog
— Unix syslog library routines¶
This module provides an interface to the Unix syslog
library routines.
Refer to the Unix manual pages for a detailed description of the syslog
facility.
Availability: Unix, not WASI, not iOS.
This module wraps the system syslog
family of routines. A pure Python
library that can speak to a syslog server is available in the
logging.handlers
module as SysLogHandler
.
The module defines the following functions:
- syslog.syslog(message)¶
- syslog.syslog(priority, message)
Send the string message to the system logger. A trailing newline is added if necessary. Each message is tagged with a priority composed of a facility and a level. The optional priority argument, which defaults to
LOG_INFO
, determines the message priority. If the facility is not encoded in priority using logical-or (LOG_INFO | LOG_USER
), the value given in theopenlog()
call is used.If
openlog()
has not been called prior to the call tosyslog()
,openlog()
will be called with no arguments.Raises an auditing event
syslog.syslog
with argumentspriority
,message
.Changed in version 3.2: In previous versions,
openlog()
would not be called automatically if it wasn’t called prior to the call tosyslog()
, deferring to the syslog implementation to callopenlog()
.Changed in version 3.12: This function is restricted in subinterpreters. (Only code that runs in multiple interpreters is affected and the restriction is not relevant for most users.)
openlog()
must be called in the main interpreter beforesyslog()
may be used in a subinterpreter. Otherwise it will raiseRuntimeError
.
- syslog.openlog([ident[, logoption[, facility]]])¶
Logging options of subsequent
syslog()
calls can be set by callingopenlog()
.syslog()
will callopenlog()
with no arguments if the log is not currently open.The optional ident keyword argument is a string which is prepended to every message, and defaults to
sys.argv[0]
with leading path components stripped. The optional logoption keyword argument (default is 0) is a bit field – see below for possible values to combine. The optional facility keyword argument (default isLOG_USER
) sets the default facility for messages which do not have a facility explicitly encoded.Raises an auditing event
syslog.openlog
with argumentsident
,logoption
,facility
.Changed in version 3.2: In previous versions, keyword arguments were not allowed, and ident was required.
Changed in version 3.12: This function is restricted in subinterpreters. (Only code that runs in multiple interpreters is affected and the restriction is not relevant for most users.) This may only be called in the main interpreter. It will raise
RuntimeError
if called in a subinterpreter.
- syslog.closelog()¶
Reset the syslog module values and call the system library
closelog()
.This causes the module to behave as it does when initially imported. For example,
openlog()
will be called on the firstsyslog()
call (ifopenlog()
hasn’t already been called), and ident and otheropenlog()
parameters are reset to defaults.Raises an auditing event
syslog.closelog
with no arguments.Changed in version 3.12: This function is restricted in subinterpreters. (Only code that runs in multiple interpreters is affected and the restriction is not relevant for most users.) This may only be called in the main interpreter. It will raise
RuntimeError
if called in a subinterpreter.
- syslog.setlogmask(maskpri)¶
Set the priority mask to maskpri and return the previous mask value. Calls to
syslog()
with a priority level not set in maskpri are ignored. The default is to log all priorities. The functionLOG_MASK(pri)
calculates the mask for the individual priority pri. The functionLOG_UPTO(pri)
calculates the mask for all priorities up to and including pri.Raises an auditing event
syslog.setlogmask
with argumentmaskpri
.
The module defines the following constants:
- syslog.LOG_EMERG¶
- syslog.LOG_ALERT¶
- syslog.LOG_CRIT¶
- syslog.LOG_ERR¶
- syslog.LOG_WARNING¶
- syslog.LOG_NOTICE¶
- syslog.LOG_INFO¶
- syslog.LOG_DEBUG¶
Priority levels (high to low).
- syslog.LOG_AUTH¶
- syslog.LOG_AUTHPRIV¶
- syslog.LOG_CRON¶
- syslog.LOG_DAEMON¶
- syslog.LOG_FTP¶
- syslog.LOG_INSTALL¶
- syslog.LOG_KERN¶
- syslog.LOG_LAUNCHD¶
- syslog.LOG_LPR¶
- syslog.LOG_MAIL¶
- syslog.LOG_NETINFO¶
- syslog.LOG_NEWS¶
- syslog.LOG_RAS¶
- syslog.LOG_REMOTEAUTH¶
- syslog.LOG_SYSLOG¶
- syslog.LOG_USER¶
- syslog.LOG_UUCP¶
- syslog.LOG_LOCAL0¶
- syslog.LOG_LOCAL1¶
- syslog.LOG_LOCAL2¶
- syslog.LOG_LOCAL3¶
- syslog.LOG_LOCAL4¶
- syslog.LOG_LOCAL5¶
- syslog.LOG_LOCAL6¶
- syslog.LOG_LOCAL7¶
Facilities, depending on availability in
<syslog.h>
forLOG_AUTHPRIV
,LOG_FTP
,LOG_NETINFO
,LOG_REMOTEAUTH
,LOG_INSTALL
andLOG_RAS
.Changed in version 3.13: Added
LOG_FTP
,LOG_NETINFO
,LOG_REMOTEAUTH
,LOG_INSTALL
,LOG_RAS
, andLOG_LAUNCHD
.
- syslog.LOG_PID¶
- syslog.LOG_CONS¶
- syslog.LOG_NDELAY¶
- syslog.LOG_ODELAY¶
- syslog.LOG_NOWAIT¶
- syslog.LOG_PERROR¶
Log options, depending on availability in
<syslog.h>
forLOG_ODELAY
,LOG_NOWAIT
andLOG_PERROR
.
Examples¶
Simple example¶
A simple set of examples:
import syslog
syslog.syslog('Processing started')
if error:
syslog.syslog(syslog.LOG_ERR, 'Processing started')
An example of setting some log options, these would include the process ID in logged messages, and write the messages to the destination facility used for mail logging:
syslog.openlog(logoption=syslog.LOG_PID, facility=syslog.LOG_MAIL)
syslog.syslog('E-mail processing initiated...')


— Resource usage information

resource
— Resource usage information¶
This module provides basic mechanisms for measuring and controlling system resources utilized by a program.
Availability: Unix, not WASI.
Symbolic constants are used to specify particular system resources and to request usage information about either the current process or its children.
An OSError
is raised on syscall failure.
Resource Limits¶
Resources usage can be limited using the setrlimit()
function described
below. Each resource is controlled by a pair of limits: a soft limit and a hard
limit. The soft limit is the current limit, and may be lowered or raised by a
process over time. The soft limit can never exceed the hard limit. The hard
limit can be lowered to any value greater than the soft limit, but not raised.
(Only processes with the effective UID of the super-user can raise a hard
limit.)
The specific resources that can be limited are system dependent. They are described in the getrlimit(2) man page. The resources listed below are supported when the underlying operating system supports them; resources which cannot be checked or controlled by the operating system are not defined in this module for those platforms.
- resource.RLIM_INFINITY¶
Constant used to represent the limit for an unlimited resource.
- resource.getrlimit(resource)¶
Returns a tuple
(soft, hard)
with the current soft and hard limits of resource. RaisesValueError
if an invalid resource is specified, orerror
if the underlying system call fails unexpectedly.
- resource.setrlimit(resource, limits)¶
Sets new limits of consumption of resource. The limits argument must be a tuple
(soft, hard)
of two integers describing the new limits. A value ofRLIM_INFINITY
can be used to request a limit that is unlimited.Raises
ValueError
if an invalid resource is specified, if the new soft limit exceeds the hard limit, or if a process tries to raise its hard limit. Specifying a limit ofRLIM_INFINITY
when the hard or system limit for that resource is not unlimited will result in aValueError
. A process with the effective UID of super-user can request any valid limit value, including unlimited, butValueError
will still be raised if the requested limit exceeds the system imposed limit.setrlimit
may also raiseerror
if the underlying system call fails.VxWorks only supports setting
RLIMIT_NOFILE
.Raises an auditing event
resource.setrlimit
with argumentsresource
,limits
.
- resource.prlimit(pid, resource[, limits])¶
Combines
setrlimit()
andgetrlimit()
in one function and supports to get and set the resources limits of an arbitrary process. If pid is 0, then the call applies to the current process. resource and limits have the same meaning as insetrlimit()
, except that limits is optional.When limits is not given the function returns the resource limit of the process pid. When limits is given the resource limit of the process is set and the former resource limit is returned.
Raises
ProcessLookupError
when pid can’t be found andPermissionError
when the user doesn’t haveCAP_SYS_RESOURCE
for the process.Raises an auditing event
resource.prlimit
with argumentspid
,resource
,limits
.Availability: Linux >= 2.6.36 with glibc >= 2.13.
Added in version 3.4.
These symbols define resources whose consumption can be controlled using the
setrlimit()
and getrlimit()
functions described below. The values of
these symbols are exactly the constants used by C programs.
The Unix man page for getrlimit(2) lists the available resources. Note that not all systems use the same symbol or same value to denote the same resource. This module does not attempt to mask platform differences — symbols not defined for a platform will not be available from this module on that platform.
- resource.RLIMIT_CORE¶
The maximum size (in bytes) of a core file that the current process can create. This may result in the creation of a partial core file if a larger core would be required to contain the entire process image.
- resource.RLIMIT_CPU¶
The maximum amount of processor time (in seconds) that a process can use. If this limit is exceeded, a
SIGXCPU
signal is sent to the process. (See thesignal
module documentation for information about how to catch this signal and do something useful, e.g. flush open files to disk.)
- resource.RLIMIT_FSIZE¶
The maximum size of a file which the process may create.
- resource.RLIMIT_DATA¶
The maximum size (in bytes) of the process’s heap.
- resource.RLIMIT_STACK¶
The maximum size (in bytes) of the call stack for the current process. This only affects the stack of the main thread in a multi-threaded process.
- resource.RLIMIT_RSS¶
The maximum resident set size that should be made available to the process.
- resource.RLIMIT_NPROC¶
The maximum number of processes the current process may create.
- resource.RLIMIT_NOFILE¶
The maximum number of open file descriptors for the current process.
- resource.RLIMIT_OFILE¶
The BSD name for
RLIMIT_NOFILE
.
- resource.RLIMIT_MEMLOCK¶
The maximum address space which may be locked in memory.
- resource.RLIMIT_VMEM¶
The largest area of mapped memory which the process may occupy. Usually an alias of
RLIMIT_AS
.Availability: Solaris, FreeBSD, NetBSD.
- resource.RLIMIT_AS¶
The maximum area (in bytes) of address space which may be taken by the process.
- resource.RLIMIT_MSGQUEUE¶
The number of bytes that can be allocated for POSIX message queues.
Availability: Linux >= 2.6.8.
Added in version 3.4.
- resource.RLIMIT_NICE¶
The ceiling for the process’s nice level (calculated as 20 - rlim_cur).
Availability: Linux >= 2.6.12.
Added in version 3.4.
- resource.RLIMIT_RTPRIO¶
The ceiling of the real-time priority.
Availability: Linux >= 2.6.12.
Added in version 3.4.
- resource.RLIMIT_RTTIME¶
The time limit (in microseconds) on CPU time that a process can spend under real-time scheduling without making a blocking syscall.
Availability: Linux >= 2.6.25.
Added in version 3.4.
- resource.RLIMIT_SIGPENDING¶
The number of signals which the process may queue.
Availability: Linux >= 2.6.8.
Added in version 3.4.
- resource.RLIMIT_SBSIZE¶
The maximum size (in bytes) of socket buffer usage for this user. This limits the amount of network memory, and hence the amount of mbufs, that this user may hold at any time.
Availability: FreeBSD, NetBSD.
Added in version 3.4.
- resource.RLIMIT_SWAP¶
The maximum size (in bytes) of the swap space that may be reserved or used by all of this user id’s processes. This limit is enforced only if bit 1 of the vm.overcommit sysctl is set. Please see tuning(7) for a complete description of this sysctl.
Availability: FreeBSD >= 8.
Added in version 3.4.
- resource.RLIMIT_NPTS¶
The maximum number of pseudo-terminals created by this user id.
Availability: FreeBSD >= 8.
Added in version 3.4.
- resource.RLIMIT_KQUEUES¶
The maximum number of kqueues this user id is allowed to create.
Availability: FreeBSD >= 11.
Added in version 3.10.
Resource Usage¶
These functions are used to retrieve resource usage information:
- resource.getrusage(who)¶
This function returns an object that describes the resources consumed by either the current process or its children, as specified by the who parameter. The who parameter should be specified using one of the
RUSAGE_*
constants described below.A simple example:
from resource import * import time # a non CPU-bound task time.sleep(3) print(getrusage(RUSAGE_SELF)) # a CPU-bound task for i in range(10 ** 8): _ = 1 + 1 print(getrusage(RUSAGE_SELF))
The fields of the return value each describe how a particular system resource has been used, e.g. amount of time spent running in user mode or number of times the process was swapped out of main memory. Some values are dependent on the clock tick interval, e.g. the amount of memory the process is using.
For backward compatibility, the return value is also accessible as a tuple of 16 elements.
The fields
ru_utime
andru_stime
of the return value are floating-point values representing the amount of time spent executing in user mode and the amount of time spent executing in system mode, respectively. The remaining values are integers. Consult the getrusage(2) man page for detailed information about these values. A brief summary is presented here:Index
Field
Resource
0
ru_utime
time in user mode (float seconds)
1
ru_stime
time in system mode (float seconds)
2
ru_maxrss
maximum resident set size
3
ru_ixrss
shared memory size
4
ru_idrss
unshared memory size
5
ru_isrss
unshared stack size
6
ru_minflt
page faults not requiring I/O
7
ru_majflt
page faults requiring I/O
8
ru_nswap
number of swap outs
9
ru_inblock
block input operations
10
ru_oublock
block output operations
11
ru_msgsnd
messages sent
12
ru_msgrcv
messages received
13
ru_nsignals
signals received
14
ru_nvcsw
voluntary context switches
15
ru_nivcsw
involuntary context switches
This function will raise a
ValueError
if an invalid who parameter is specified. It may also raiseerror
exception in unusual circumstances.
- resource.getpagesize()¶
Returns the number of bytes in a system page. (This need not be the same as the hardware page size.)
The following RUSAGE_*
symbols are passed to the getrusage()
function to specify which processes information should be provided for.
- resource.RUSAGE_SELF¶
Pass to
getrusage()
to request resources consumed by the calling process, which is the sum of resources used by all threads in the process.
- resource.RUSAGE_CHILDREN¶
Pass to
getrusage()
to request resources consumed by child processes of the calling process which have been terminated and waited for.
- resource.RUSAGE_BOTH¶
Pass to
getrusage()
to request resources consumed by both the current process and child processes. May not be available on all systems.
- resource.RUSAGE_THREAD¶
Pass to
getrusage()
to request resources consumed by the current thread. May not be available on all systems.Added in version 3.2.


— The

fcntl
— The fcntl
and ioctl
system calls¶
This module performs file and I/O control on file descriptors. It is an
interface to the fcntl()
and ioctl()
Unix routines.
See the fcntl(2) and ioctl(2) Unix manual pages
for full details.
Availability: Unix, not WASI.
All functions in this module take a file descriptor fd as their first
argument. This can be an integer file descriptor, such as returned by
sys.stdin.fileno()
, or an io.IOBase
object, such as sys.stdin
itself, which provides a fileno()
that returns a genuine file
descriptor.
Changed in version 3.3: Operations in this module used to raise an IOError
where they now
raise an OSError
.
Changed in version 3.8: The fcntl
module now contains F_ADD_SEALS
, F_GET_SEALS
, and
F_SEAL_*
constants for sealing of os.memfd_create()
file
descriptors.
Changed in version 3.9: On macOS, the fcntl
module exposes the F_GETPATH
constant,
which obtains the path of a file from a file descriptor.
On Linux(>=3.15), the fcntl
module exposes the F_OFD_GETLK
,
F_OFD_SETLK
and F_OFD_SETLKW
constants, which are used when working
with open file description locks.
Changed in version 3.10: On Linux >= 2.6.11, the fcntl
module exposes the F_GETPIPE_SZ
and
F_SETPIPE_SZ
constants, which allow to check and modify a pipe’s size
respectively.
Changed in version 3.11: On FreeBSD, the fcntl
module exposes the F_DUP2FD
and
F_DUP2FD_CLOEXEC
constants, which allow to duplicate a file descriptor,
the latter setting FD_CLOEXEC
flag in addition.
Changed in version 3.12: On Linux >= 4.5, the fcntl
module exposes the FICLONE
and
FICLONERANGE
constants, which allow to share some data of one file with
another file by reflinking on some filesystems (e.g., btrfs, OCFS2, and
XFS). This behavior is commonly referred to as “copy-on-write”.
Changed in version 3.13: On Linux >= 2.6.32, the fcntl
module exposes the
F_GETOWN_EX
, F_SETOWN_EX
, F_OWNER_TID
, F_OWNER_PID
, F_OWNER_PGRP
constants, which allow to direct I/O availability signals
to a specific thread, process, or process group.
On Linux >= 4.13, the fcntl
module exposes the
F_GET_RW_HINT
, F_SET_RW_HINT
, F_GET_FILE_RW_HINT
,
F_SET_FILE_RW_HINT
, and RWH_WRITE_LIFE_*
constants, which allow
to inform the kernel about the relative expected lifetime of writes on
a given inode or via a particular open file description.
On Linux >= 5.1 and NetBSD, the fcntl
module exposes the
F_SEAL_FUTURE_WRITE
constant for use with F_ADD_SEALS
and
F_GET_SEALS
operations.
On FreeBSD, the fcntl
module exposes the F_READAHEAD
, F_ISUNIONSTACK
, and F_KINFO
constants.
On macOS and FreeBSD, the fcntl
module exposes the F_RDAHEAD
constant.
On NetBSD and AIX, the fcntl
module exposes the F_CLOSEM
constant.
On NetBSD, the fcntl
module exposes the F_MAXFD
constant.
On macOS and NetBSD, the fcntl
module exposes the F_GETNOSIGPIPE
and F_SETNOSIGPIPE
constant.
Changed in version 3.14: On Linux >= 6.1, the fcntl
module exposes the F_DUPFD_QUERY
to query a file descriptor pointing to the same file.
The module defines the following functions:
- fcntl.fcntl(fd, cmd, arg=0, /)¶
Perform the operation cmd on file descriptor fd (file objects providing a
fileno()
method are accepted as well). The values used for cmd are operating system dependent, and are available as constants in thefcntl
module, using the same names as used in the relevant C header files. The argument arg can either be an integer value, a bytes-like object, or a string. The type and size of arg must match the type and size of the argument of the operation as specified in the relevant C documentation.When arg is an integer, the function returns the integer return value of the C
fcntl()
call.When the argument is bytes-like object, it represents a binary structure, for example, created by
struct.pack()
. A string value is encoded to binary using the UTF-8 encoding. The binary data is copied to a buffer whose address is passed to the Cfcntl()
call. The return value after a successful call is the contents of the buffer, converted to abytes
object. The length of the returned object will be the same as the length of the arg argument. This is limited to 1024 bytes.If the
fcntl()
call fails, anOSError
is raised.Note
If the type or the size of arg does not match the type or size of the argument of the operation (for example, if an integer is passed when a pointer is expected, or the information returned in the buffer by the operating system is larger than 1024 bytes), this is most likely to result in a segmentation violation or a more subtle data corruption.
Raises an auditing event
fcntl.fcntl
with argumentsfd
,cmd
,arg
.Changed in version 3.14: Add support of arbitrary bytes-like objects, not only
bytes
.
- fcntl.ioctl(fd, request, arg=0, mutate_flag=True, /)¶
This function is identical to the
fcntl()
function, except that the argument handling is even more complicated.The request parameter is limited to values that can fit in 32-bits or 64-bits, depending on the platform. Additional constants of interest for use as the request argument can be found in the
termios
module, under the same names as used in the relevant C header files.The parameter arg can be an integer, a bytes-like object, or a string. The type and size of arg must match the type and size of the argument of the operation as specified in the relevant C documentation.
If arg does not support the read-write buffer interface or the mutate_flag is false, behavior is as for the
fcntl()
function.If arg supports the read-write buffer interface (like
bytearray
) and mutate_flag is true (the default), then the buffer is (in effect) passed to the underlyingioctl()
system call, the latter’s return code is passed back to the calling Python, and the buffer’s new contents reflect the action of theioctl()
. This is a slight simplification, because if the supplied buffer is less than 1024 bytes long it is first copied into a static buffer 1024 bytes long which is then passed toioctl()
and copied back into the supplied buffer.If the
ioctl()
call fails, anOSError
exception is raised.Note
If the type or size of arg does not match the type or size of the operation’s argument (for example, if an integer is passed when a pointer is expected, or the information returned in the buffer by the operating system is larger than 1024 bytes, or the size of the mutable bytes-like object is too small), this is most likely to result in a segmentation violation or a more subtle data corruption.
An example:
>>> import array, fcntl, struct, termios, os >>> os.getpgrp() 13341 >>> struct.unpack('h', fcntl.ioctl(0, termios.TIOCGPGRP, " "))[0] 13341 >>> buf = array.array('h', [0]) >>> fcntl.ioctl(0, termios.TIOCGPGRP, buf, 1) 0 >>> buf array('h', [13341])
Raises an auditing event
fcntl.ioctl
with argumentsfd
,request
,arg
.Changed in version 3.14: The GIL is always released during a system call. System calls failing with EINTR are automatically retried.
- fcntl.flock(fd, operation, /)¶
Perform the lock operation operation on file descriptor fd (file objects providing a
fileno()
method are accepted as well). See the Unix manual flock(2) for details. (On some systems, this function is emulated usingfcntl()
.)If the
flock()
call fails, anOSError
exception is raised.Raises an auditing event
fcntl.flock
with argumentsfd
,operation
.
- fcntl.lockf(fd, cmd, len=0, start=0, whence=0, /)¶
This is essentially a wrapper around the
fcntl()
locking calls. fd is the file descriptor (file objects providing afileno()
method are accepted as well) of the file to lock or unlock, and cmd is one of the following values:- fcntl.LOCK_UN¶
Release an existing lock.
- fcntl.LOCK_SH¶
Acquire a shared lock.
- fcntl.LOCK_EX¶
Acquire an exclusive lock.
- fcntl.LOCK_NB¶
Bitwise OR with any of the other three
LOCK_*
constants to make the request non-blocking.
If
LOCK_NB
is used and the lock cannot be acquired, anOSError
will be raised and the exception will have an errno attribute set toEACCES
orEAGAIN
(depending on the operating system; for portability, check for both values). On at least some systems,LOCK_EX
can only be used if the file descriptor refers to a file opened for writing.len is the number of bytes to lock, start is the byte offset at which the lock starts, relative to whence, and whence is as with
io.IOBase.seek()
, specifically:0
– relative to the start of the file (os.SEEK_SET
)1
– relative to the current buffer position (os.SEEK_CUR
)2
– relative to the end of the file (os.SEEK_END
)
The default for start is 0, which means to start at the beginning of the file. The default for len is 0 which means to lock to the end of the file. The default for whence is also 0.
Raises an auditing event
fcntl.lockf
with argumentsfd
,cmd
,len
,start
,whence
.
Examples (all on a SVR4 compliant system):
import struct, fcntl, os
f = open(...)
rv = fcntl.fcntl(f, fcntl.F_SETFL, os.O_NDELAY)
lockdata = struct.pack('hhllhh', fcntl.F_WRLCK, 0, 0, 0, 0, 0)
rv = fcntl.fcntl(f, fcntl.F_SETLKW, lockdata)
Note that in the first example the return value variable rv will hold an
integer value; in the second example it will hold a bytes
object. The
structure lay-out for the lockdata variable is system dependent — therefore
using the flock()
call may be better.