doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
faulthandler.enable(file=sys.stderr, all_threads=True) Enable the fault handler: install handlers for the SIGSEGV, SIGFPE, SIGABRT, SIGBUS and SIGILL signals to dump the Python traceback. If all_threads is True, produce tracebacks for every running thread. Otherwise, dump only the current thread. The file must be kept open until the fault handler is disabled: see issue with file descriptors. Changed in version 3.5: Added support for passing file descriptor to this function. Changed in version 3.6: On Windows, a handler for Windows exception is also installed.
python.library.faulthandler#faulthandler.enable
faulthandler.is_enabled() Check if the fault handler is enabled.
python.library.faulthandler#faulthandler.is_enabled
faulthandler.register(signum, file=sys.stderr, all_threads=True, chain=False) Register a user signal: install a handler for the signum signal to dump the traceback of all threads, or of the current thread if all_threads is False, into file. Call the previous handler if chain is True. The file must be kept open until the signal is unregistered by unregister(): see issue with file descriptors. Not available on Windows. Changed in version 3.5: Added support for passing file descriptor to this function.
python.library.faulthandler#faulthandler.register
faulthandler.unregister(signum) Unregister a user signal: uninstall the handler of the signum signal installed by register(). Return True if the signal was registered, False otherwise. Not available on Windows.
python.library.faulthandler#faulthandler.unregister
fcntl — The fcntl and ioctl system calls This module performs file control and I/O control on file descriptors. It is an interface to the fcntl() and ioctl() Unix routines. For a complete description of these calls, see fcntl(2) and ioctl(2) Unix manual pages. 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 working with open file description locks. 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 the fcntl module, using the same names as used in the relevant C header files. The argument arg can either be an integer value, or a bytes object. With an integer value, the return value of this function is the integer return value of the C fcntl() call. When the argument is bytes it represents a binary structure, e.g. created by struct.pack(). The binary data is copied to a buffer whose address is passed to the C fcntl() call. The return value after a successful call is the contents of the buffer, converted to a bytes 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 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. If the fcntl() fails, an OSError is raised. Raises an auditing event fcntl.fcntl with arguments fd, cmd, arg. 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. 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 one of an integer, an object supporting the read-only buffer interface (like bytes) or an object supporting the read-write buffer interface (like bytearray). In all but the last case, behaviour is as for the fcntl() function. If a mutable buffer is passed, then the behaviour is determined by the value of the mutate_flag parameter. If it is false, the buffer’s mutability is ignored and behaviour is as for a read-only buffer, except that the 1024 byte limit mentioned above is avoided – so long as the buffer you pass is at least as long as what the operating system wants to put there, things should work. If mutate_flag is true (the default), then the buffer is (in effect) passed to the underlying ioctl() system call, the latter’s return code is passed back to the calling Python, and the buffer’s new contents reflect the action of the ioctl(). 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 to ioctl() and copied back into the supplied buffer. If the ioctl() fails, an OSError exception is raised. 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 arguments fd, request, arg. 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 using fcntl().) If the flock() fails, an OSError exception is raised. Raises an auditing event fcntl.flock with arguments fd, 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 a fileno() method are accepted as well) of the file to lock or unlock, and cmd is one of the following values: LOCK_UN – unlock LOCK_SH – acquire a shared lock LOCK_EX – acquire an exclusive lock When cmd is LOCK_SH or LOCK_EX, it can also be bitwise ORed with LOCK_NB to avoid blocking on lock acquisition. If LOCK_NB is used and the lock cannot be acquired, an OSError will be raised and the exception will have an errno attribute set to EACCES or EAGAIN (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 arguments fd, 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. See also Module os If the locking flags O_SHLOCK and O_EXLOCK are present in the os module (on BSD only), the os.open() function provides an alternative to the lockf() and flock() functions.
python.library.fcntl
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 the fcntl module, using the same names as used in the relevant C header files. The argument arg can either be an integer value, or a bytes object. With an integer value, the return value of this function is the integer return value of the C fcntl() call. When the argument is bytes it represents a binary structure, e.g. created by struct.pack(). The binary data is copied to a buffer whose address is passed to the C fcntl() call. The return value after a successful call is the contents of the buffer, converted to a bytes 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 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. If the fcntl() fails, an OSError is raised. Raises an auditing event fcntl.fcntl with arguments fd, cmd, arg.
python.library.fcntl#fcntl.fcntl
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 using fcntl().) If the flock() fails, an OSError exception is raised. Raises an auditing event fcntl.flock with arguments fd, operation.
python.library.fcntl#fcntl.flock
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. 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 one of an integer, an object supporting the read-only buffer interface (like bytes) or an object supporting the read-write buffer interface (like bytearray). In all but the last case, behaviour is as for the fcntl() function. If a mutable buffer is passed, then the behaviour is determined by the value of the mutate_flag parameter. If it is false, the buffer’s mutability is ignored and behaviour is as for a read-only buffer, except that the 1024 byte limit mentioned above is avoided – so long as the buffer you pass is at least as long as what the operating system wants to put there, things should work. If mutate_flag is true (the default), then the buffer is (in effect) passed to the underlying ioctl() system call, the latter’s return code is passed back to the calling Python, and the buffer’s new contents reflect the action of the ioctl(). 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 to ioctl() and copied back into the supplied buffer. If the ioctl() fails, an OSError exception is raised. 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 arguments fd, request, arg.
python.library.fcntl#fcntl.ioctl
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 a fileno() method are accepted as well) of the file to lock or unlock, and cmd is one of the following values: LOCK_UN – unlock LOCK_SH – acquire a shared lock LOCK_EX – acquire an exclusive lock When cmd is LOCK_SH or LOCK_EX, it can also be bitwise ORed with LOCK_NB to avoid blocking on lock acquisition. If LOCK_NB is used and the lock cannot be acquired, an OSError will be raised and the exception will have an errno attribute set to EACCES or EAGAIN (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 arguments fd, cmd, len, start, whence.
python.library.fcntl#fcntl.lockf
filecmp — File and Directory Comparisons Source code: Lib/filecmp.py The filecmp module defines functions to compare files and directories, with various optional time/correctness trade-offs. For comparing files, see also the difflib module. The filecmp module defines the following functions: filecmp.cmp(f1, f2, shallow=True) Compare the files named f1 and f2, returning True if they seem equal, False otherwise. If shallow is true, files with identical os.stat() signatures are taken to be equal. Otherwise, the contents of the files are compared. Note that no external programs are called from this function, giving it portability and efficiency. This function uses a cache for past comparisons and the results, with cache entries invalidated if the os.stat() information for the file changes. The entire cache may be cleared using clear_cache(). filecmp.cmpfiles(dir1, dir2, common, shallow=True) Compare the files in the two directories dir1 and dir2 whose names are given by common. Returns three lists of file names: match, mismatch, errors. match contains the list of files that match, mismatch contains the names of those that don’t, and errors lists the names of files which could not be compared. Files are listed in errors if they don’t exist in one of the directories, the user lacks permission to read them or if the comparison could not be done for some other reason. The shallow parameter has the same meaning and default value as for filecmp.cmp(). For example, cmpfiles('a', 'b', ['c', 'd/e']) will compare a/c with b/c and a/d/e with b/d/e. 'c' and 'd/e' will each be in one of the three returned lists. filecmp.clear_cache() Clear the filecmp cache. This may be useful if a file is compared so quickly after it is modified that it is within the mtime resolution of the underlying filesystem. New in version 3.4. The dircmp class class filecmp.dircmp(a, b, ignore=None, hide=None) Construct a new directory comparison object, to compare the directories a and b. ignore is a list of names to ignore, and defaults to filecmp.DEFAULT_IGNORES. hide is a list of names to hide, and defaults to [os.curdir, os.pardir]. The dircmp class compares files by doing shallow comparisons as described for filecmp.cmp(). The dircmp class provides the following methods: report() Print (to sys.stdout) a comparison between a and b. report_partial_closure() Print a comparison between a and b and common immediate subdirectories. report_full_closure() Print a comparison between a and b and common subdirectories (recursively). The dircmp class offers a number of interesting attributes that may be used to get various bits of information about the directory trees being compared. Note that via __getattr__() hooks, all attributes are computed lazily, so there is no speed penalty if only those attributes which are lightweight to compute are used. left The directory a. right The directory b. left_list Files and subdirectories in a, filtered by hide and ignore. right_list Files and subdirectories in b, filtered by hide and ignore. common Files and subdirectories in both a and b. left_only Files and subdirectories only in a. right_only Files and subdirectories only in b. common_dirs Subdirectories in both a and b. common_files Files in both a and b. common_funny Names in both a and b, such that the type differs between the directories, or names for which os.stat() reports an error. same_files Files which are identical in both a and b, using the class’s file comparison operator. diff_files Files which are in both a and b, whose contents differ according to the class’s file comparison operator. funny_files Files which are in both a and b, but could not be compared. subdirs A dictionary mapping names in common_dirs to dircmp objects. filecmp.DEFAULT_IGNORES New in version 3.4. List of directories ignored by dircmp by default. Here is a simplified example of using the subdirs attribute to search recursively through two directories to show common different files: >>> from filecmp import dircmp >>> def print_diff_files(dcmp): ... for name in dcmp.diff_files: ... print("diff_file %s found in %s and %s" % (name, dcmp.left, ... dcmp.right)) ... for sub_dcmp in dcmp.subdirs.values(): ... print_diff_files(sub_dcmp) ... >>> dcmp = dircmp('dir1', 'dir2') >>> print_diff_files(dcmp)
python.library.filecmp
filecmp.clear_cache() Clear the filecmp cache. This may be useful if a file is compared so quickly after it is modified that it is within the mtime resolution of the underlying filesystem. New in version 3.4.
python.library.filecmp#filecmp.clear_cache
filecmp.cmp(f1, f2, shallow=True) Compare the files named f1 and f2, returning True if they seem equal, False otherwise. If shallow is true, files with identical os.stat() signatures are taken to be equal. Otherwise, the contents of the files are compared. Note that no external programs are called from this function, giving it portability and efficiency. This function uses a cache for past comparisons and the results, with cache entries invalidated if the os.stat() information for the file changes. The entire cache may be cleared using clear_cache().
python.library.filecmp#filecmp.cmp
filecmp.cmpfiles(dir1, dir2, common, shallow=True) Compare the files in the two directories dir1 and dir2 whose names are given by common. Returns three lists of file names: match, mismatch, errors. match contains the list of files that match, mismatch contains the names of those that don’t, and errors lists the names of files which could not be compared. Files are listed in errors if they don’t exist in one of the directories, the user lacks permission to read them or if the comparison could not be done for some other reason. The shallow parameter has the same meaning and default value as for filecmp.cmp(). For example, cmpfiles('a', 'b', ['c', 'd/e']) will compare a/c with b/c and a/d/e with b/d/e. 'c' and 'd/e' will each be in one of the three returned lists.
python.library.filecmp#filecmp.cmpfiles
filecmp.DEFAULT_IGNORES New in version 3.4. List of directories ignored by dircmp by default.
python.library.filecmp#filecmp.DEFAULT_IGNORES
class filecmp.dircmp(a, b, ignore=None, hide=None) Construct a new directory comparison object, to compare the directories a and b. ignore is a list of names to ignore, and defaults to filecmp.DEFAULT_IGNORES. hide is a list of names to hide, and defaults to [os.curdir, os.pardir]. The dircmp class compares files by doing shallow comparisons as described for filecmp.cmp(). The dircmp class provides the following methods: report() Print (to sys.stdout) a comparison between a and b. report_partial_closure() Print a comparison between a and b and common immediate subdirectories. report_full_closure() Print a comparison between a and b and common subdirectories (recursively). The dircmp class offers a number of interesting attributes that may be used to get various bits of information about the directory trees being compared. Note that via __getattr__() hooks, all attributes are computed lazily, so there is no speed penalty if only those attributes which are lightweight to compute are used. left The directory a. right The directory b. left_list Files and subdirectories in a, filtered by hide and ignore. right_list Files and subdirectories in b, filtered by hide and ignore. common Files and subdirectories in both a and b. left_only Files and subdirectories only in a. right_only Files and subdirectories only in b. common_dirs Subdirectories in both a and b. common_files Files in both a and b. common_funny Names in both a and b, such that the type differs between the directories, or names for which os.stat() reports an error. same_files Files which are identical in both a and b, using the class’s file comparison operator. diff_files Files which are in both a and b, whose contents differ according to the class’s file comparison operator. funny_files Files which are in both a and b, but could not be compared. subdirs A dictionary mapping names in common_dirs to dircmp objects.
python.library.filecmp#filecmp.dircmp
common Files and subdirectories in both a and b.
python.library.filecmp#filecmp.dircmp.common
common_dirs Subdirectories in both a and b.
python.library.filecmp#filecmp.dircmp.common_dirs
common_files Files in both a and b.
python.library.filecmp#filecmp.dircmp.common_files
common_funny Names in both a and b, such that the type differs between the directories, or names for which os.stat() reports an error.
python.library.filecmp#filecmp.dircmp.common_funny
diff_files Files which are in both a and b, whose contents differ according to the class’s file comparison operator.
python.library.filecmp#filecmp.dircmp.diff_files
funny_files Files which are in both a and b, but could not be compared.
python.library.filecmp#filecmp.dircmp.funny_files
left The directory a.
python.library.filecmp#filecmp.dircmp.left
left_list Files and subdirectories in a, filtered by hide and ignore.
python.library.filecmp#filecmp.dircmp.left_list
left_only Files and subdirectories only in a.
python.library.filecmp#filecmp.dircmp.left_only
report() Print (to sys.stdout) a comparison between a and b.
python.library.filecmp#filecmp.dircmp.report
report_full_closure() Print a comparison between a and b and common subdirectories (recursively).
python.library.filecmp#filecmp.dircmp.report_full_closure
report_partial_closure() Print a comparison between a and b and common immediate subdirectories.
python.library.filecmp#filecmp.dircmp.report_partial_closure
right The directory b.
python.library.filecmp#filecmp.dircmp.right
right_list Files and subdirectories in b, filtered by hide and ignore.
python.library.filecmp#filecmp.dircmp.right_list
right_only Files and subdirectories only in b.
python.library.filecmp#filecmp.dircmp.right_only
same_files Files which are identical in both a and b, using the class’s file comparison operator.
python.library.filecmp#filecmp.dircmp.same_files
subdirs A dictionary mapping names in common_dirs to dircmp objects.
python.library.filecmp#filecmp.dircmp.subdirs
exception FileExistsError Raised when trying to create a file or directory which already exists. Corresponds to errno EEXIST.
python.library.exceptions#FileExistsError
fileinput — Iterate over lines from multiple input streams Source code: Lib/fileinput.py This module implements a helper class and functions to quickly write a loop over standard input or a list of files. If you just want to read or write one file see open(). The typical use is: import fileinput for line in fileinput.input(): process(line) This iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty. If a filename is '-', it is also replaced by sys.stdin and the optional arguments mode and openhook are ignored. To specify an alternative list of filenames, pass it as the first argument to input(). A single file name is also allowed. All files are opened in text mode by default, but you can override this by specifying the mode parameter in the call to input() or FileInput. If an I/O error occurs during opening or reading a file, OSError is raised. Changed in version 3.3: IOError used to be raised; it is now an alias of OSError. If sys.stdin is used more than once, the second and further use will return no lines, except perhaps for interactive use, or if it has been explicitly reset (e.g. using sys.stdin.seek(0)). Empty files are opened and immediately closed; the only time their presence in the list of filenames is noticeable at all is when the last file opened is empty. Lines are returned with any newlines intact, which means that the last line in a file may not have one. You can control how files are opened by providing an opening hook via the openhook parameter to fileinput.input() or FileInput(). The hook must be a function that takes two arguments, filename and mode, and returns an accordingly opened file-like object. Two useful hooks are already provided by this module. The following function is the primary interface of this module: fileinput.input(files=None, inplace=False, backup='', *, mode='r', openhook=None) Create an instance of the FileInput class. The instance will be used as global state for the functions of this module, and is also returned to use during iteration. The parameters to this function will be passed along to the constructor of the FileInput class. The FileInput instance can be used as a context manager in the with statement. In this example, input is closed after the with statement is exited, even if an exception occurs: with fileinput.input(files=('spam.txt', 'eggs.txt')) as f: for line in f: process(line) Changed in version 3.2: Can be used as a context manager. Changed in version 3.8: The keyword parameters mode and openhook are now keyword-only. The following functions use the global state created by fileinput.input(); if there is no active state, RuntimeError is raised. fileinput.filename() Return the name of the file currently being read. Before the first line has been read, returns None. fileinput.fileno() Return the integer “file descriptor” for the current file. When no file is opened (before the first line and between files), returns -1. fileinput.lineno() Return the cumulative line number of the line that has just been read. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line. fileinput.filelineno() Return the line number in the current file. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line within the file. fileinput.isfirstline() Return True if the line just read is the first line of its file, otherwise return False. fileinput.isstdin() Return True if the last line was read from sys.stdin, otherwise return False. fileinput.nextfile() Close the current file so that the next iteration will read the first line from the next file (if any); lines not read from the file will not count towards the cumulative line count. The filename is not changed until after the first line of the next file has been read. Before the first line has been read, this function has no effect; it cannot be used to skip the first file. After the last line of the last file has been read, this function has no effect. fileinput.close() Close the sequence. The class which implements the sequence behavior provided by the module is available for subclassing as well: class fileinput.FileInput(files=None, inplace=False, backup='', *, mode='r', openhook=None) Class FileInput is the implementation; its methods filename(), fileno(), lineno(), filelineno(), isfirstline(), isstdin(), nextfile() and close() correspond to the functions of the same name in the module. In addition it has a readline() method which returns the next input line, and a __getitem__() method which implements the sequence behavior. The sequence must be accessed in strictly sequential order; random access and readline() cannot be mixed. With mode you can specify which file mode will be passed to open(). It must be one of 'r', 'rU', 'U' and 'rb'. The openhook, when given, must be a function that takes two arguments, filename and mode, and returns an accordingly opened file-like object. You cannot use inplace and openhook together. A FileInput instance can be used as a context manager in the with statement. In this example, input is closed after the with statement is exited, even if an exception occurs: with FileInput(files=('spam.txt', 'eggs.txt')) as input: process(input) Changed in version 3.2: Can be used as a context manager. Deprecated since version 3.4: The 'rU' and 'U' modes. Deprecated since version 3.8: Support for __getitem__() method is deprecated. Changed in version 3.8: The keyword parameter mode and openhook are now keyword-only. Optional in-place filtering: if the keyword argument inplace=True is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). This makes it possible to write a filter that rewrites its input file in place. If the backup parameter is given (typically as backup='.<some extension>'), it specifies the extension for the backup file, and the backup file remains around; by default, the extension is '.bak' and it is deleted when the output file is closed. In-place filtering is disabled when standard input is read. The two following opening hooks are provided by this module: fileinput.hook_compressed(filename, mode) Transparently opens files compressed with gzip and bzip2 (recognized by the extensions '.gz' and '.bz2') using the gzip and bz2 modules. If the filename extension is not '.gz' or '.bz2', the file is opened normally (ie, using open() without any decompression). Usage example: fi = fileinput.FileInput(openhook=fileinput.hook_compressed) fileinput.hook_encoded(encoding, errors=None) Returns a hook which opens each file with open(), using the given encoding and errors to read the file. Usage example: fi = fileinput.FileInput(openhook=fileinput.hook_encoded("utf-8", "surrogateescape")) Changed in version 3.6: Added the optional errors parameter.
python.library.fileinput
fileinput.close() Close the sequence.
python.library.fileinput#fileinput.close
class fileinput.FileInput(files=None, inplace=False, backup='', *, mode='r', openhook=None) Class FileInput is the implementation; its methods filename(), fileno(), lineno(), filelineno(), isfirstline(), isstdin(), nextfile() and close() correspond to the functions of the same name in the module. In addition it has a readline() method which returns the next input line, and a __getitem__() method which implements the sequence behavior. The sequence must be accessed in strictly sequential order; random access and readline() cannot be mixed. With mode you can specify which file mode will be passed to open(). It must be one of 'r', 'rU', 'U' and 'rb'. The openhook, when given, must be a function that takes two arguments, filename and mode, and returns an accordingly opened file-like object. You cannot use inplace and openhook together. A FileInput instance can be used as a context manager in the with statement. In this example, input is closed after the with statement is exited, even if an exception occurs: with FileInput(files=('spam.txt', 'eggs.txt')) as input: process(input) Changed in version 3.2: Can be used as a context manager. Deprecated since version 3.4: The 'rU' and 'U' modes. Deprecated since version 3.8: Support for __getitem__() method is deprecated. Changed in version 3.8: The keyword parameter mode and openhook are now keyword-only.
python.library.fileinput#fileinput.FileInput
fileinput.filelineno() Return the line number in the current file. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line within the file.
python.library.fileinput#fileinput.filelineno
fileinput.filename() Return the name of the file currently being read. Before the first line has been read, returns None.
python.library.fileinput#fileinput.filename
fileinput.fileno() Return the integer “file descriptor” for the current file. When no file is opened (before the first line and between files), returns -1.
python.library.fileinput#fileinput.fileno
fileinput.hook_compressed(filename, mode) Transparently opens files compressed with gzip and bzip2 (recognized by the extensions '.gz' and '.bz2') using the gzip and bz2 modules. If the filename extension is not '.gz' or '.bz2', the file is opened normally (ie, using open() without any decompression). Usage example: fi = fileinput.FileInput(openhook=fileinput.hook_compressed)
python.library.fileinput#fileinput.hook_compressed
fileinput.hook_encoded(encoding, errors=None) Returns a hook which opens each file with open(), using the given encoding and errors to read the file. Usage example: fi = fileinput.FileInput(openhook=fileinput.hook_encoded("utf-8", "surrogateescape")) Changed in version 3.6: Added the optional errors parameter.
python.library.fileinput#fileinput.hook_encoded
fileinput.input(files=None, inplace=False, backup='', *, mode='r', openhook=None) Create an instance of the FileInput class. The instance will be used as global state for the functions of this module, and is also returned to use during iteration. The parameters to this function will be passed along to the constructor of the FileInput class. The FileInput instance can be used as a context manager in the with statement. In this example, input is closed after the with statement is exited, even if an exception occurs: with fileinput.input(files=('spam.txt', 'eggs.txt')) as f: for line in f: process(line) Changed in version 3.2: Can be used as a context manager. Changed in version 3.8: The keyword parameters mode and openhook are now keyword-only.
python.library.fileinput#fileinput.input
fileinput.isfirstline() Return True if the line just read is the first line of its file, otherwise return False.
python.library.fileinput#fileinput.isfirstline
fileinput.isstdin() Return True if the last line was read from sys.stdin, otherwise return False.
python.library.fileinput#fileinput.isstdin
fileinput.lineno() Return the cumulative line number of the line that has just been read. Before the first line has been read, returns 0. After the last line of the last file has been read, returns the line number of that line.
python.library.fileinput#fileinput.lineno
fileinput.nextfile() Close the current file so that the next iteration will read the first line from the next file (if any); lines not read from the file will not count towards the cumulative line count. The filename is not changed until after the first line of the next file has been read. Before the first line has been read, this function has no effect; it cannot be used to skip the first file. After the last line of the last file has been read, this function has no effect.
python.library.fileinput#fileinput.nextfile
exception FileNotFoundError Raised when a file or directory is requested but doesn’t exist. Corresponds to errno ENOENT.
python.library.exceptions#FileNotFoundError
filter(function, iterable) Construct an iterator from those elements of iterable for which function returns true. iterable may be either a sequence, a container which supports iteration, or an iterator. If function is None, the identity function is assumed, that is, all elements of iterable that are false are removed. Note that filter(function, iterable) is equivalent to the generator expression (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None. See itertools.filterfalse() for the complementary function that returns elements of iterable for which function returns false.
python.library.functions#filter
class float([x]) Return a floating point number constructed from a number or string x. If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be '+' or '-'; a '+' sign has no effect on the value produced. The argument may also be a string representing a NaN (not-a-number), or a positive or negative infinity. More precisely, the input must conform to the following grammar after leading and trailing whitespace characters are removed: sign ::= "+" | "-" infinity ::= "Infinity" | "inf" nan ::= "nan" numeric_value ::= floatnumber | infinity | nan numeric_string ::= [sign] numeric_value Here floatnumber is the form of a Python floating-point literal, described in Floating point literals. Case is not significant, so, for example, “inf”, “Inf”, “INFINITY” and “iNfINity” are all acceptable spellings for positive infinity. Otherwise, if the argument is an integer or a floating point number, a floating point number with the same value (within Python’s floating point precision) is returned. If the argument is outside the range of a Python float, an OverflowError will be raised. For a general Python object x, float(x) delegates to x.__float__(). If __float__() is not defined then it falls back to __index__(). If no argument is given, 0.0 is returned. Examples: >>> float('+1.23') 1.23 >>> float(' -12345\n') -12345.0 >>> float('1e-003') 0.001 >>> float('+1E6') 1000000.0 >>> float('-Infinity') -inf The float type is described in Numeric Types — int, float, complex. Changed in version 3.6: Grouping digits with underscores as in code literals is allowed. Changed in version 3.7: x is now a positional-only parameter. Changed in version 3.8: Falls back to __index__() if __float__() is not defined.
python.library.functions#float
float.as_integer_ratio() Return a pair of integers whose ratio is exactly equal to the original float and with a positive denominator. Raises OverflowError on infinities and a ValueError on NaNs.
python.library.stdtypes#float.as_integer_ratio
classmethod float.fromhex(s) Class method to return the float represented by a hexadecimal string s. The string s may have leading and trailing whitespace.
python.library.stdtypes#float.fromhex
float.hex() Return a representation of a floating-point number as a hexadecimal string. For finite floating-point numbers, this representation will always include a leading 0x and a trailing p and exponent.
python.library.stdtypes#float.hex
float.is_integer() Return True if the float instance is finite with integral value, and False otherwise: >>> (-2.0).is_integer() True >>> (3.2).is_integer() False
python.library.stdtypes#float.is_integer
exception FloatingPointError Not currently used.
python.library.exceptions#FloatingPointError
fnmatch — Unix filename pattern matching Source code: Lib/fnmatch.py This module provides support for Unix shell-style wildcards, which are not the same as regular expressions (which are documented in the re module). The special characters used in shell-style wildcards are: Pattern Meaning * matches everything ? matches any single character [seq] matches any character in seq [!seq] matches any character not in seq For a literal match, wrap the meta-characters in brackets. For example, '[?]' matches the character '?'. Note that the filename separator ('/' on Unix) is not special to this module. See module glob for pathname expansion (glob uses filter() to match pathname segments). Similarly, filenames starting with a period are not special for this module, and are matched by the * and ? patterns. fnmatch.fnmatch(filename, pattern) Test whether the filename string matches the pattern string, returning True or False. Both parameters are case-normalized using os.path.normcase(). fnmatchcase() can be used to perform a case-sensitive comparison, regardless of whether that’s standard for the operating system. This example will print all file names in the current directory with the extension .txt: import fnmatch import os for file in os.listdir('.'): if fnmatch.fnmatch(file, '*.txt'): print(file) fnmatch.fnmatchcase(filename, pattern) Test whether filename matches pattern, returning True or False; the comparison is case-sensitive and does not apply os.path.normcase(). fnmatch.filter(names, pattern) Construct a list from those elements of the iterable names that match pattern. It is the same as [n for n in names if fnmatch(n, pattern)], but implemented more efficiently. fnmatch.translate(pattern) Return the shell-style pattern converted to a regular expression for using with re.match(). Example: >>> import fnmatch, re >>> >>> regex = fnmatch.translate('*.txt') >>> regex '(?s:.*\\.txt)\\Z' >>> reobj = re.compile(regex) >>> reobj.match('foobar.txt') <re.Match object; span=(0, 10), match='foobar.txt'> See also Module glob Unix shell-style path expansion.
python.library.fnmatch
fnmatch.filter(names, pattern) Construct a list from those elements of the iterable names that match pattern. It is the same as [n for n in names if fnmatch(n, pattern)], but implemented more efficiently.
python.library.fnmatch#fnmatch.filter
fnmatch.fnmatch(filename, pattern) Test whether the filename string matches the pattern string, returning True or False. Both parameters are case-normalized using os.path.normcase(). fnmatchcase() can be used to perform a case-sensitive comparison, regardless of whether that’s standard for the operating system. This example will print all file names in the current directory with the extension .txt: import fnmatch import os for file in os.listdir('.'): if fnmatch.fnmatch(file, '*.txt'): print(file)
python.library.fnmatch#fnmatch.fnmatch
fnmatch.fnmatchcase(filename, pattern) Test whether filename matches pattern, returning True or False; the comparison is case-sensitive and does not apply os.path.normcase().
python.library.fnmatch#fnmatch.fnmatchcase
fnmatch.translate(pattern) Return the shell-style pattern converted to a regular expression for using with re.match(). Example: >>> import fnmatch, re >>> >>> regex = fnmatch.translate('*.txt') >>> regex '(?s:.*\\.txt)\\Z' >>> reobj = re.compile(regex) >>> reobj.match('foobar.txt') <re.Match object; span=(0, 10), match='foobar.txt'>
python.library.fnmatch#fnmatch.translate
format(value[, format_spec]) Convert a value to a “formatted” representation, as controlled by format_spec. The interpretation of format_spec will depend on the type of the value argument, however there is a standard formatting syntax that is used by most built-in types: Format Specification Mini-Language. The default format_spec is an empty string which usually gives the same effect as calling str(value). A call to format(value, format_spec) is translated to type(value).__format__(value, format_spec) which bypasses the instance dictionary when searching for the value’s __format__() method. A TypeError exception is raised if the method search reaches object and the format_spec is non-empty, or if either the format_spec or the return value are not strings. Changed in version 3.4: object().__format__(format_spec) raises TypeError if format_spec is not an empty string.
python.library.functions#format
fractions — Rational numbers Source code: Lib/fractions.py The fractions module provides support for rational number arithmetic. A Fraction instance can be constructed from a pair of integers, from another rational number, or from a string. class fractions.Fraction(numerator=0, denominator=1) class fractions.Fraction(other_fraction) class fractions.Fraction(float) class fractions.Fraction(decimal) class fractions.Fraction(string) The first version requires that numerator and denominator are instances of numbers.Rational and returns a new Fraction instance with value numerator/denominator. If denominator is 0, it raises a ZeroDivisionError. The second version requires that other_fraction is an instance of numbers.Rational and returns a Fraction instance with the same value. The next two versions accept either a float or a decimal.Decimal instance, and return a Fraction instance with exactly the same value. Note that due to the usual issues with binary floating-point (see Floating Point Arithmetic: Issues and Limitations), the argument to Fraction(1.1) is not exactly equal to 11/10, and so Fraction(1.1) does not return Fraction(11, 10) as one might expect. (But see the documentation for the limit_denominator() method below.) The last version of the constructor expects a string or unicode instance. The usual form for this instance is: [sign] numerator ['/' denominator] where the optional sign may be either ‘+’ or ‘-‘ and numerator and denominator (if present) are strings of decimal digits. In addition, any string that represents a finite value and is accepted by the float constructor is also accepted by the Fraction constructor. In either form the input string may also have leading and/or trailing whitespace. Here are some examples: >>> from fractions import Fraction >>> Fraction(16, -10) Fraction(-8, 5) >>> Fraction(123) Fraction(123, 1) >>> Fraction() Fraction(0, 1) >>> Fraction('3/7') Fraction(3, 7) >>> Fraction(' -3/7 ') Fraction(-3, 7) >>> Fraction('1.414213 \t\n') Fraction(1414213, 1000000) >>> Fraction('-.125') Fraction(-1, 8) >>> Fraction('7e-6') Fraction(7, 1000000) >>> Fraction(2.25) Fraction(9, 4) >>> Fraction(1.1) Fraction(2476979795053773, 2251799813685248) >>> from decimal import Decimal >>> Fraction(Decimal('1.1')) Fraction(11, 10) The Fraction class inherits from the abstract base class numbers.Rational, and implements all of the methods and operations from that class. Fraction instances are hashable, and should be treated as immutable. In addition, Fraction has the following properties and methods: Changed in version 3.2: The Fraction constructor now accepts float and decimal.Decimal instances. Changed in version 3.9: The math.gcd() function is now used to normalize the numerator and denominator. math.gcd() always return a int type. Previously, the GCD type depended on numerator and denominator. numerator Numerator of the Fraction in lowest term. denominator Denominator of the Fraction in lowest term. as_integer_ratio() Return a tuple of two integers, whose ratio is equal to the Fraction and with a positive denominator. New in version 3.8. from_float(flt) This class method constructs a Fraction representing the exact value of flt, which must be a float. Beware that Fraction.from_float(0.3) is not the same value as Fraction(3, 10). Note From Python 3.2 onwards, you can also construct a Fraction instance directly from a float. from_decimal(dec) This class method constructs a Fraction representing the exact value of dec, which must be a decimal.Decimal instance. Note From Python 3.2 onwards, you can also construct a Fraction instance directly from a decimal.Decimal instance. limit_denominator(max_denominator=1000000) Finds and returns the closest Fraction to self that has denominator at most max_denominator. This method is useful for finding rational approximations to a given floating-point number: >>> from fractions import Fraction >>> Fraction('3.1415926535897932').limit_denominator(1000) Fraction(355, 113) or for recovering a rational number that’s represented as a float: >>> from math import pi, cos >>> Fraction(cos(pi/3)) Fraction(4503599627370497, 9007199254740992) >>> Fraction(cos(pi/3)).limit_denominator() Fraction(1, 2) >>> Fraction(1.1).limit_denominator() Fraction(11, 10) __floor__() Returns the greatest int <= self. This method can also be accessed through the math.floor() function: >>> from math import floor >>> floor(Fraction(355, 113)) 3 __ceil__() Returns the least int >= self. This method can also be accessed through the math.ceil() function. __round__() __round__(ndigits) The first version returns the nearest int to self, rounding half to even. The second version rounds self to the nearest multiple of Fraction(1, 10**ndigits) (logically, if ndigits is negative), again rounding half toward even. This method can also be accessed through the round() function. See also Module numbers The abstract base classes making up the numeric tower.
python.library.fractions
class fractions.Fraction(numerator=0, denominator=1) class fractions.Fraction(other_fraction) class fractions.Fraction(float) class fractions.Fraction(decimal) class fractions.Fraction(string) The first version requires that numerator and denominator are instances of numbers.Rational and returns a new Fraction instance with value numerator/denominator. If denominator is 0, it raises a ZeroDivisionError. The second version requires that other_fraction is an instance of numbers.Rational and returns a Fraction instance with the same value. The next two versions accept either a float or a decimal.Decimal instance, and return a Fraction instance with exactly the same value. Note that due to the usual issues with binary floating-point (see Floating Point Arithmetic: Issues and Limitations), the argument to Fraction(1.1) is not exactly equal to 11/10, and so Fraction(1.1) does not return Fraction(11, 10) as one might expect. (But see the documentation for the limit_denominator() method below.) The last version of the constructor expects a string or unicode instance. The usual form for this instance is: [sign] numerator ['/' denominator] where the optional sign may be either ‘+’ or ‘-‘ and numerator and denominator (if present) are strings of decimal digits. In addition, any string that represents a finite value and is accepted by the float constructor is also accepted by the Fraction constructor. In either form the input string may also have leading and/or trailing whitespace. Here are some examples: >>> from fractions import Fraction >>> Fraction(16, -10) Fraction(-8, 5) >>> Fraction(123) Fraction(123, 1) >>> Fraction() Fraction(0, 1) >>> Fraction('3/7') Fraction(3, 7) >>> Fraction(' -3/7 ') Fraction(-3, 7) >>> Fraction('1.414213 \t\n') Fraction(1414213, 1000000) >>> Fraction('-.125') Fraction(-1, 8) >>> Fraction('7e-6') Fraction(7, 1000000) >>> Fraction(2.25) Fraction(9, 4) >>> Fraction(1.1) Fraction(2476979795053773, 2251799813685248) >>> from decimal import Decimal >>> Fraction(Decimal('1.1')) Fraction(11, 10) The Fraction class inherits from the abstract base class numbers.Rational, and implements all of the methods and operations from that class. Fraction instances are hashable, and should be treated as immutable. In addition, Fraction has the following properties and methods: Changed in version 3.2: The Fraction constructor now accepts float and decimal.Decimal instances. Changed in version 3.9: The math.gcd() function is now used to normalize the numerator and denominator. math.gcd() always return a int type. Previously, the GCD type depended on numerator and denominator. numerator Numerator of the Fraction in lowest term. denominator Denominator of the Fraction in lowest term. as_integer_ratio() Return a tuple of two integers, whose ratio is equal to the Fraction and with a positive denominator. New in version 3.8. from_float(flt) This class method constructs a Fraction representing the exact value of flt, which must be a float. Beware that Fraction.from_float(0.3) is not the same value as Fraction(3, 10). Note From Python 3.2 onwards, you can also construct a Fraction instance directly from a float. from_decimal(dec) This class method constructs a Fraction representing the exact value of dec, which must be a decimal.Decimal instance. Note From Python 3.2 onwards, you can also construct a Fraction instance directly from a decimal.Decimal instance. limit_denominator(max_denominator=1000000) Finds and returns the closest Fraction to self that has denominator at most max_denominator. This method is useful for finding rational approximations to a given floating-point number: >>> from fractions import Fraction >>> Fraction('3.1415926535897932').limit_denominator(1000) Fraction(355, 113) or for recovering a rational number that’s represented as a float: >>> from math import pi, cos >>> Fraction(cos(pi/3)) Fraction(4503599627370497, 9007199254740992) >>> Fraction(cos(pi/3)).limit_denominator() Fraction(1, 2) >>> Fraction(1.1).limit_denominator() Fraction(11, 10) __floor__() Returns the greatest int <= self. This method can also be accessed through the math.floor() function: >>> from math import floor >>> floor(Fraction(355, 113)) 3 __ceil__() Returns the least int >= self. This method can also be accessed through the math.ceil() function. __round__() __round__(ndigits) The first version returns the nearest int to self, rounding half to even. The second version rounds self to the nearest multiple of Fraction(1, 10**ndigits) (logically, if ndigits is negative), again rounding half toward even. This method can also be accessed through the round() function.
python.library.fractions#fractions.Fraction
as_integer_ratio() Return a tuple of two integers, whose ratio is equal to the Fraction and with a positive denominator. New in version 3.8.
python.library.fractions#fractions.Fraction.as_integer_ratio
denominator Denominator of the Fraction in lowest term.
python.library.fractions#fractions.Fraction.denominator
from_decimal(dec) This class method constructs a Fraction representing the exact value of dec, which must be a decimal.Decimal instance. Note From Python 3.2 onwards, you can also construct a Fraction instance directly from a decimal.Decimal instance.
python.library.fractions#fractions.Fraction.from_decimal
from_float(flt) This class method constructs a Fraction representing the exact value of flt, which must be a float. Beware that Fraction.from_float(0.3) is not the same value as Fraction(3, 10). Note From Python 3.2 onwards, you can also construct a Fraction instance directly from a float.
python.library.fractions#fractions.Fraction.from_float
limit_denominator(max_denominator=1000000) Finds and returns the closest Fraction to self that has denominator at most max_denominator. This method is useful for finding rational approximations to a given floating-point number: >>> from fractions import Fraction >>> Fraction('3.1415926535897932').limit_denominator(1000) Fraction(355, 113) or for recovering a rational number that’s represented as a float: >>> from math import pi, cos >>> Fraction(cos(pi/3)) Fraction(4503599627370497, 9007199254740992) >>> Fraction(cos(pi/3)).limit_denominator() Fraction(1, 2) >>> Fraction(1.1).limit_denominator() Fraction(11, 10)
python.library.fractions#fractions.Fraction.limit_denominator
numerator Numerator of the Fraction in lowest term.
python.library.fractions#fractions.Fraction.numerator
__ceil__() Returns the least int >= self. This method can also be accessed through the math.ceil() function.
python.library.fractions#fractions.Fraction.__ceil__
__floor__() Returns the greatest int <= self. This method can also be accessed through the math.floor() function: >>> from math import floor >>> floor(Fraction(355, 113)) 3
python.library.fractions#fractions.Fraction.__floor__
__round__() __round__(ndigits) The first version returns the nearest int to self, rounding half to even. The second version rounds self to the nearest multiple of Fraction(1, 10**ndigits) (logically, if ndigits is negative), again rounding half toward even. This method can also be accessed through the round() function.
python.library.fractions#fractions.Fraction.__round__
class frozenset([iterable]) Return a new frozenset object, optionally with elements taken from iterable. frozenset is a built-in class. See frozenset and Set Types — set, frozenset for documentation about this class. For other containers see the built-in set, list, tuple, and dict classes, as well as the collections module.
python.library.functions#frozenset
class set([iterable]) class frozenset([iterable]) Return a new set or frozenset object whose elements are taken from iterable. The elements of a set must be hashable. To represent sets of sets, the inner sets must be frozenset objects. If iterable is not specified, a new empty set is returned. Sets can be created by several means: Use a comma-separated list of elements within braces: {'jack', 'sjoerd'} Use a set comprehension: {c for c in 'abracadabra' if c not in 'abc'} Use the type constructor: set(), set('foobar'), set(['a', 'b', 'foo']) Instances of set and frozenset provide the following operations: len(s) Return the number of elements in set s (cardinality of s). x in s Test x for membership in s. x not in s Test x for non-membership in s. isdisjoint(other) Return True if the set has no elements in common with other. Sets are disjoint if and only if their intersection is the empty set. issubset(other) set <= other Test whether every element in the set is in other. set < other Test whether the set is a proper subset of other, that is, set <= other and set != other. issuperset(other) set >= other Test whether every element in other is in the set. set > other Test whether the set is a proper superset of other, that is, set >= other and set != other. union(*others) set | other | ... Return a new set with elements from the set and all others. intersection(*others) set & other & ... Return a new set with elements common to the set and all others. difference(*others) set - other - ... Return a new set with elements in the set that are not in the others. symmetric_difference(other) set ^ other Return a new set with elements in either the set or other but not both. copy() Return a shallow copy of the set. Note, the non-operator versions of union(), intersection(), difference(), and symmetric_difference(), issubset(), and issuperset() methods will accept any iterable as an argument. In contrast, their operator based counterparts require their arguments to be sets. This precludes error-prone constructions like set('abc') & 'cbs' in favor of the more readable set('abc').intersection('cbs'). Both set and frozenset support set to set comparisons. Two sets are equal if and only if every element of each set is contained in the other (each is a subset of the other). A set is less than another set if and only if the first set is a proper subset of the second set (is a subset, but is not equal). A set is greater than another set if and only if the first set is a proper superset of the second set (is a superset, but is not equal). Instances of set are compared to instances of frozenset based on their members. For example, set('abc') == frozenset('abc') returns True and so does set('abc') in set([frozenset('abc')]). The subset and equality comparisons do not generalize to a total ordering function. For example, any two nonempty disjoint sets are not equal and are not subsets of each other, so all of the following return False: a<b, a==b, or a>b. Since sets only define partial ordering (subset relationships), the output of the list.sort() method is undefined for lists of sets. Set elements, like dictionary keys, must be hashable. Binary operations that mix set instances with frozenset return the type of the first operand. For example: frozenset('ab') | set('bc') returns an instance of frozenset. The following table lists operations available for set that do not apply to immutable instances of frozenset: update(*others) set |= other | ... Update the set, adding elements from all others. intersection_update(*others) set &= other & ... Update the set, keeping only elements found in it and all others. difference_update(*others) set -= other | ... Update the set, removing elements found in others. symmetric_difference_update(other) set ^= other Update the set, keeping only elements found in either set, but not in both. add(elem) Add element elem to the set. remove(elem) Remove element elem from the set. Raises KeyError if elem is not contained in the set. discard(elem) Remove element elem from the set if it is present. pop() Remove and return an arbitrary element from the set. Raises KeyError if the set is empty. clear() Remove all elements from the set. Note, the non-operator versions of the update(), intersection_update(), difference_update(), and symmetric_difference_update() methods will accept any iterable as an argument. Note, the elem argument to the __contains__(), remove(), and discard() methods may be a set. To support searching for an equivalent frozenset, a temporary one is created from elem.
python.library.stdtypes#frozenset
add(elem) Add element elem to the set.
python.library.stdtypes#frozenset.add
clear() Remove all elements from the set.
python.library.stdtypes#frozenset.clear
copy() Return a shallow copy of the set.
python.library.stdtypes#frozenset.copy
difference(*others) set - other - ... Return a new set with elements in the set that are not in the others.
python.library.stdtypes#frozenset.difference
difference_update(*others) set -= other | ... Update the set, removing elements found in others.
python.library.stdtypes#frozenset.difference_update
discard(elem) Remove element elem from the set if it is present.
python.library.stdtypes#frozenset.discard
intersection(*others) set & other & ... Return a new set with elements common to the set and all others.
python.library.stdtypes#frozenset.intersection
intersection_update(*others) set &= other & ... Update the set, keeping only elements found in it and all others.
python.library.stdtypes#frozenset.intersection_update
isdisjoint(other) Return True if the set has no elements in common with other. Sets are disjoint if and only if their intersection is the empty set.
python.library.stdtypes#frozenset.isdisjoint
issubset(other) set <= other Test whether every element in the set is in other.
python.library.stdtypes#frozenset.issubset
issuperset(other) set >= other Test whether every element in other is in the set.
python.library.stdtypes#frozenset.issuperset
pop() Remove and return an arbitrary element from the set. Raises KeyError if the set is empty.
python.library.stdtypes#frozenset.pop
remove(elem) Remove element elem from the set. Raises KeyError if elem is not contained in the set.
python.library.stdtypes#frozenset.remove
symmetric_difference(other) set ^ other Return a new set with elements in either the set or other but not both.
python.library.stdtypes#frozenset.symmetric_difference
symmetric_difference_update(other) set ^= other Update the set, keeping only elements found in either set, but not in both.
python.library.stdtypes#frozenset.symmetric_difference_update
union(*others) set | other | ... Return a new set with elements from the set and all others.
python.library.stdtypes#frozenset.union
update(*others) set |= other | ... Update the set, adding elements from all others.
python.library.stdtypes#frozenset.update
ftplib — FTP protocol client Source code: Lib/ftplib.py This module defines the class FTP and a few related items. The FTP class implements the client side of the FTP protocol. You can use this to write Python programs that perform a variety of automated FTP jobs, such as mirroring other FTP servers. It is also used by the module urllib.request to handle URLs that use FTP. For more information on FTP (File Transfer Protocol), see Internet RFC 959. The default encoding is UTF-8, following RFC 2640. Here’s a sample session using the ftplib module: >>> from ftplib import FTP >>> ftp = FTP('ftp.us.debian.org') # connect to host, default port >>> ftp.login() # user anonymous, passwd anonymous@ '230 Login successful.' >>> ftp.cwd('debian') # change into "debian" directory >>> ftp.retrlines('LIST') # list directory contents -rw-rw-r-- 1 1176 1176 1063 Jun 15 10:18 README ... drwxr-sr-x 5 1176 1176 4096 Dec 19 2000 pool drwxr-sr-x 4 1176 1176 4096 Nov 17 2008 project drwxr-xr-x 3 1176 1176 4096 Oct 10 2012 tools '226 Directory send OK.' >>> with open('README', 'wb') as fp: >>> ftp.retrbinary('RETR README', fp.write) '226 Transfer complete.' >>> ftp.quit() The module defines the following items: class ftplib.FTP(host='', user='', passwd='', acct='', timeout=None, source_address=None, *, encoding='utf-8') Return a new instance of the FTP class. When host is given, the method call connect(host) is made. When user is given, additionally the method call login(user, passwd, acct) is made (where passwd and acct default to the empty string when not given). The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if is not specified, the global default timeout setting will be used). source_address is a 2-tuple (host, port) for the socket to bind to as its source address before connecting. The encoding parameter specifies the encoding for directories and filenames. The FTP class supports the with statement, e.g.: >>> from ftplib import FTP >>> with FTP("ftp1.at.proftpd.org") as ftp: ... ftp.login() ... ftp.dir() ... '230 Anonymous login ok, restrictions apply.' dr-xr-xr-x 9 ftp ftp 154 May 6 10:43 . dr-xr-xr-x 9 ftp ftp 154 May 6 10:43 .. dr-xr-xr-x 5 ftp ftp 4096 May 6 10:43 CentOS dr-xr-xr-x 3 ftp ftp 18 Jul 10 2008 Fedora >>> Changed in version 3.2: Support for the with statement was added. Changed in version 3.3: source_address parameter was added. Changed in version 3.9: If the timeout parameter is set to be zero, it will raise a ValueError to prevent the creation of a non-blocking socket. The encoding parameter was added, and the default was changed from Latin-1 to UTF-8 to follow RFC 2640. class ftplib.FTP_TLS(host='', user='', passwd='', acct='', keyfile=None, certfile=None, context=None, timeout=None, source_address=None, *, encoding='utf-8') A FTP subclass which adds TLS support to FTP as described in RFC 4217. Connect as usual to port 21 implicitly securing the FTP control connection before authenticating. Securing the data connection requires the user to explicitly ask for it by calling the prot_p() method. context is a ssl.SSLContext object which allows bundling SSL configuration options, certificates and private keys into a single (potentially long-lived) structure. Please read Security considerations for best practices. keyfile and certfile are a legacy alternative to context – they can point to PEM-formatted private key and certificate chain files (respectively) for the SSL connection. New in version 3.2. Changed in version 3.3: source_address parameter was added. Changed in version 3.4: The class now supports hostname check with ssl.SSLContext.check_hostname and Server Name Indication (see ssl.HAS_SNI). Deprecated since version 3.6: keyfile and certfile are deprecated in favor of context. Please use ssl.SSLContext.load_cert_chain() instead, or let ssl.create_default_context() select the system’s trusted CA certificates for you. Changed in version 3.9: If the timeout parameter is set to be zero, it will raise a ValueError to prevent the creation of a non-blocking socket. The encoding parameter was added, and the default was changed from Latin-1 to UTF-8 to follow RFC 2640. Here’s a sample session using the FTP_TLS class: >>> ftps = FTP_TLS('ftp.pureftpd.org') >>> ftps.login() '230 Anonymous user logged in' >>> ftps.prot_p() '200 Data protection level set to "private"' >>> ftps.nlst() ['6jack', 'OpenBSD', 'antilink', 'blogbench', 'bsdcam', 'clockspeed', 'djbdns-jedi', 'docs', 'eaccelerator-jedi', 'favicon.ico', 'francotone', 'fugu', 'ignore', 'libpuzzle', 'metalog', 'minidentd', 'misc', 'mysql-udf-global-user-variables', 'php-jenkins-hash', 'php-skein-hash', 'php-webdav', 'phpaudit', 'phpbench', 'pincaster', 'ping', 'posto', 'pub', 'public', 'public_keys', 'pure-ftpd', 'qscan', 'qtc', 'sharedance', 'skycache', 'sound', 'tmp', 'ucarp'] exception ftplib.error_reply Exception raised when an unexpected reply is received from the server. exception ftplib.error_temp Exception raised when an error code signifying a temporary error (response codes in the range 400–499) is received. exception ftplib.error_perm Exception raised when an error code signifying a permanent error (response codes in the range 500–599) is received. exception ftplib.error_proto Exception raised when a reply is received from the server that does not fit the response specifications of the File Transfer Protocol, i.e. begin with a digit in the range 1–5. ftplib.all_errors The set of all exceptions (as a tuple) that methods of FTP instances may raise as a result of problems with the FTP connection (as opposed to programming errors made by the caller). This set includes the four exceptions listed above as well as OSError and EOFError. See also Module netrc Parser for the .netrc file format. The file .netrc is typically used by FTP clients to load user authentication information before prompting the user. FTP Objects Several methods are available in two flavors: one for handling text files and another for binary files. These are named for the command which is used followed by lines for the text version or binary for the binary version. FTP instances have the following methods: FTP.set_debuglevel(level) Set the instance’s debugging level. This controls the amount of debugging output printed. The default, 0, produces no debugging output. A value of 1 produces a moderate amount of debugging output, generally a single line per request. A value of 2 or higher produces the maximum amount of debugging output, logging each line sent and received on the control connection. FTP.connect(host='', port=0, timeout=None, source_address=None) Connect to the given host and port. The default port number is 21, as specified by the FTP protocol specification. It is rarely needed to specify a different port number. This function should be called only once for each instance; it should not be called at all if a host was given when the instance was created. All other methods can only be used after a connection has been made. The optional timeout parameter specifies a timeout in seconds for the connection attempt. If no timeout is passed, the global default timeout setting will be used. source_address is a 2-tuple (host, port) for the socket to bind to as its source address before connecting. Raises an auditing event ftplib.connect with arguments self, host, port. Changed in version 3.3: source_address parameter was added. FTP.getwelcome() Return the welcome message sent by the server in reply to the initial connection. (This message sometimes contains disclaimers or help information that may be relevant to the user.) FTP.login(user='anonymous', passwd='', acct='') Log in as the given user. The passwd and acct parameters are optional and default to the empty string. If no user is specified, it defaults to 'anonymous'. If user is 'anonymous', the default passwd is 'anonymous@'. This function should be called only once for each instance, after a connection has been established; it should not be called at all if a host and user were given when the instance was created. Most FTP commands are only allowed after the client has logged in. The acct parameter supplies “accounting information”; few systems implement this. FTP.abort() Abort a file transfer that is in progress. Using this does not always work, but it’s worth a try. FTP.sendcmd(cmd) Send a simple command string to the server and return the response string. Raises an auditing event ftplib.sendcmd with arguments self, cmd. FTP.voidcmd(cmd) Send a simple command string to the server and handle the response. Return nothing if a response code corresponding to success (codes in the range 200–299) is received. Raise error_reply otherwise. Raises an auditing event ftplib.sendcmd with arguments self, cmd. FTP.retrbinary(cmd, callback, blocksize=8192, rest=None) Retrieve a file in binary transfer mode. cmd should be an appropriate RETR command: 'RETR filename'. The callback function is called for each block of data received, with a single bytes argument giving the data block. The optional blocksize argument specifies the maximum chunk size to read on the low-level socket object created to do the actual transfer (which will also be the largest size of the data blocks passed to callback). A reasonable default is chosen. rest means the same thing as in the transfercmd() method. FTP.retrlines(cmd, callback=None) Retrieve a file or directory listing in the encoding specified by the encoding parameter at initialization. cmd should be an appropriate RETR command (see retrbinary()) or a command such as LIST or NLST (usually just the string 'LIST'). LIST retrieves a list of files and information about those files. NLST retrieves a list of file names. The callback function is called for each line with a string argument containing the line with the trailing CRLF stripped. The default callback prints the line to sys.stdout. FTP.set_pasv(val) Enable “passive” mode if val is true, otherwise disable passive mode. Passive mode is on by default. FTP.storbinary(cmd, fp, blocksize=8192, callback=None, rest=None) Store a file in binary transfer mode. cmd should be an appropriate STOR command: "STOR filename". fp is a file object (opened in binary mode) which is read until EOF using its read() method in blocks of size blocksize to provide the data to be stored. The blocksize argument defaults to 8192. callback is an optional single parameter callable that is called on each block of data after it is sent. rest means the same thing as in the transfercmd() method. Changed in version 3.2: rest parameter added. FTP.storlines(cmd, fp, callback=None) Store a file in line mode. cmd should be an appropriate STOR command (see storbinary()). Lines are read until EOF from the file object fp (opened in binary mode) using its readline() method to provide the data to be stored. callback is an optional single parameter callable that is called on each line after it is sent. FTP.transfercmd(cmd, rest=None) Initiate a transfer over the data connection. If the transfer is active, send an EPRT or PORT command and the transfer command specified by cmd, and accept the connection. If the server is passive, send an EPSV or PASV command, connect to it, and start the transfer command. Either way, return the socket for the connection. If optional rest is given, a REST command is sent to the server, passing rest as an argument. rest is usually a byte offset into the requested file, telling the server to restart sending the file’s bytes at the requested offset, skipping over the initial bytes. Note however that the transfercmd() method converts rest to a string with the encoding parameter specified at initialization, but no check is performed on the string’s contents. If the server does not recognize the REST command, an error_reply exception will be raised. If this happens, simply call transfercmd() without a rest argument. FTP.ntransfercmd(cmd, rest=None) Like transfercmd(), but returns a tuple of the data connection and the expected size of the data. If the expected size could not be computed, None will be returned as the expected size. cmd and rest means the same thing as in transfercmd(). FTP.mlsd(path="", facts=[]) List a directory in a standardized format by using MLSD command (RFC 3659). If path is omitted the current directory is assumed. facts is a list of strings representing the type of information desired (e.g. ["type", "size", "perm"]). Return a generator object yielding a tuple of two elements for every file found in path. First element is the file name, the second one is a dictionary containing facts about the file name. Content of this dictionary might be limited by the facts argument but server is not guaranteed to return all requested facts. New in version 3.3. FTP.nlst(argument[, ...]) Return a list of file names as returned by the NLST command. The optional argument is a directory to list (default is the current server directory). Multiple arguments can be used to pass non-standard options to the NLST command. Note If your server supports the command, mlsd() offers a better API. FTP.dir(argument[, ...]) Produce a directory listing as returned by the LIST command, printing it to standard output. The optional argument is a directory to list (default is the current server directory). Multiple arguments can be used to pass non-standard options to the LIST command. If the last argument is a function, it is used as a callback function as for retrlines(); the default prints to sys.stdout. This method returns None. Note If your server supports the command, mlsd() offers a better API. FTP.rename(fromname, toname) Rename file fromname on the server to toname. FTP.delete(filename) Remove the file named filename from the server. If successful, returns the text of the response, otherwise raises error_perm on permission errors or error_reply on other errors. FTP.cwd(pathname) Set the current directory on the server. FTP.mkd(pathname) Create a new directory on the server. FTP.pwd() Return the pathname of the current directory on the server. FTP.rmd(dirname) Remove the directory named dirname on the server. FTP.size(filename) Request the size of the file named filename on the server. On success, the size of the file is returned as an integer, otherwise None is returned. Note that the SIZE command is not standardized, but is supported by many common server implementations. FTP.quit() Send a QUIT command to the server and close the connection. This is the “polite” way to close a connection, but it may raise an exception if the server responds with an error to the QUIT command. This implies a call to the close() method which renders the FTP instance useless for subsequent calls (see below). FTP.close() Close the connection unilaterally. This should not be applied to an already closed connection such as after a successful call to quit(). After this call the FTP instance should not be used any more (after a call to close() or quit() you cannot reopen the connection by issuing another login() method). FTP_TLS Objects FTP_TLS class inherits from FTP, defining these additional objects: FTP_TLS.ssl_version The SSL version to use (defaults to ssl.PROTOCOL_SSLv23). FTP_TLS.auth() Set up a secure control connection by using TLS or SSL, depending on what is specified in the ssl_version attribute. Changed in version 3.4: The method now supports hostname check with ssl.SSLContext.check_hostname and Server Name Indication (see ssl.HAS_SNI). FTP_TLS.ccc() Revert control channel back to plaintext. This can be useful to take advantage of firewalls that know how to handle NAT with non-secure FTP without opening fixed ports. New in version 3.3. FTP_TLS.prot_p() Set up secure data connection. FTP_TLS.prot_c() Set up clear text data connection.
python.library.ftplib
ftplib.all_errors The set of all exceptions (as a tuple) that methods of FTP instances may raise as a result of problems with the FTP connection (as opposed to programming errors made by the caller). This set includes the four exceptions listed above as well as OSError and EOFError.
python.library.ftplib#ftplib.all_errors
exception ftplib.error_perm Exception raised when an error code signifying a permanent error (response codes in the range 500–599) is received.
python.library.ftplib#ftplib.error_perm
exception ftplib.error_proto Exception raised when a reply is received from the server that does not fit the response specifications of the File Transfer Protocol, i.e. begin with a digit in the range 1–5.
python.library.ftplib#ftplib.error_proto
exception ftplib.error_reply Exception raised when an unexpected reply is received from the server.
python.library.ftplib#ftplib.error_reply
exception ftplib.error_temp Exception raised when an error code signifying a temporary error (response codes in the range 400–499) is received.
python.library.ftplib#ftplib.error_temp
class ftplib.FTP(host='', user='', passwd='', acct='', timeout=None, source_address=None, *, encoding='utf-8') Return a new instance of the FTP class. When host is given, the method call connect(host) is made. When user is given, additionally the method call login(user, passwd, acct) is made (where passwd and acct default to the empty string when not given). The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if is not specified, the global default timeout setting will be used). source_address is a 2-tuple (host, port) for the socket to bind to as its source address before connecting. The encoding parameter specifies the encoding for directories and filenames. The FTP class supports the with statement, e.g.: >>> from ftplib import FTP >>> with FTP("ftp1.at.proftpd.org") as ftp: ... ftp.login() ... ftp.dir() ... '230 Anonymous login ok, restrictions apply.' dr-xr-xr-x 9 ftp ftp 154 May 6 10:43 . dr-xr-xr-x 9 ftp ftp 154 May 6 10:43 .. dr-xr-xr-x 5 ftp ftp 4096 May 6 10:43 CentOS dr-xr-xr-x 3 ftp ftp 18 Jul 10 2008 Fedora >>> Changed in version 3.2: Support for the with statement was added. Changed in version 3.3: source_address parameter was added. Changed in version 3.9: If the timeout parameter is set to be zero, it will raise a ValueError to prevent the creation of a non-blocking socket. The encoding parameter was added, and the default was changed from Latin-1 to UTF-8 to follow RFC 2640.
python.library.ftplib#ftplib.FTP
FTP.abort() Abort a file transfer that is in progress. Using this does not always work, but it’s worth a try.
python.library.ftplib#ftplib.FTP.abort
FTP.close() Close the connection unilaterally. This should not be applied to an already closed connection such as after a successful call to quit(). After this call the FTP instance should not be used any more (after a call to close() or quit() you cannot reopen the connection by issuing another login() method).
python.library.ftplib#ftplib.FTP.close
FTP.connect(host='', port=0, timeout=None, source_address=None) Connect to the given host and port. The default port number is 21, as specified by the FTP protocol specification. It is rarely needed to specify a different port number. This function should be called only once for each instance; it should not be called at all if a host was given when the instance was created. All other methods can only be used after a connection has been made. The optional timeout parameter specifies a timeout in seconds for the connection attempt. If no timeout is passed, the global default timeout setting will be used. source_address is a 2-tuple (host, port) for the socket to bind to as its source address before connecting. Raises an auditing event ftplib.connect with arguments self, host, port. Changed in version 3.3: source_address parameter was added.
python.library.ftplib#ftplib.FTP.connect