hash, sum, super, idlen, max, min, next, sumdelattr, dir, getattr, globals, locals, setattr, varsascii, format, reprinput, open, print __import__breakpoint, @classmethod, compile, eval, exec, help, @staticmethod
Draft for Information Only
Content
Python Built-in Misc Functions input() Parameters Remarks open() Parameters Remarks print() Parameters Remarks __import__() Parameters Remarks Source and Reference
Python Built-in Misc Functions
The Python interpreter has some built-in misc. io functions.
input()
input([prompt])
Parameters
type()to read a line from input.
[prompt]optional, to specify the prompt
Remarks
- If
prompt is present, input() is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
- When
EOF is read, EOFERROR is raised.
- If the
readline module was loaded, then input() will use it to provide elaborate line editing and history features.
- Raises an auditing event
builtins.input with argument prompt before reading input.
- Raises an auditing event
builtins.input/result with the result after succesfully reading input.
open()
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Parameters
open()to open and return a corresponding file object.
fileis a path-like object giving the pathname (absolute or relative to the current working directory) of the file to be opened or an integer file descriptior of the file to be wrappd. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.)
mode='r'default to string r, to specify the mode in which the file is opened
buffering=-1default to integer -1, to specify the buffering policy.
encoding=Nonedefault to None, to specify the name of encoding used to decode or encode the file.
errors=Nonedefault to None, to specify how encoding and decoding errors are to be handled.
newline=Nonedefault to None, to specify how universal newlines mode works
closefd=Truedefault to True, to specify the given file is file descriptor or filename.
opener=Nonedefault to None, to specify a custom opener.
Remarks
- If the
file cannot be opened, an OSError is raised.
mode:
CharacterMeaning
ropen for reading (default)
wopen for writing, truncating the file first
xopen for exclusive creation, aailing if the file already exists
aopen for writing, appending to the end of the file if it exist
bbinary mode
ttext mode (default)
+open for updating (reading and writing)
The default mode is r (open for reading text, synonym of rt. Modes w+ and w+b open and truncate the file. Modes r+ and r+b open the file with no truncation.
- Python distinguishes between binary and text I/O. Files opened n binary mode (including
b in the mode argument) return contents as bytes objects without any decoding. In text mode (the default, or when t is included in the mode argument, the contents of the file are returned as str, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.
- There is an additional mode character permitted,
U, which no longer has any effect, and is considered deprecated. It previously enabled universal newlines in text mode, which became the default behaviour.
- Python doesn't depend on the underlying operating system's notion of text files; all the processing is doen by Python itself, and is therefore platform-independent.
buffering:
integerMeaning
0to switch buffering off (only allowed in binary mode)
1to select line buffering (only usable in text mode).
>1to indicate the size in bytes of a fixed-size chunk buffer.
omittedthe default buffering policy works as follows:
Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device’s “block size” and falling back on io.DEFAULT_BUFFER_SIZE. On many systems, the buffer will typically be 4096 or 8192 bytes long.
“Interactive” text files (files for which isatty() returns True) use line buffering. Other text files use the policy described above for binary files.
- encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any text encoding supported by Python can be used. See the codecs module for the list of supported encodings.
error cannot be used in binary mode. A variety of standard error handlers are available, though any error handling name that has been registered with codecs.register_error() is also valid.
Standard errors are:
namemeanig
strictto raise a ValueError exception if there is an encoding error. The default value of None has the same effect.
ignoreignores errors. Note that ignoring encoding errors can lead to data loss.
replacecauses a replacement marker (such as '?') to be inserted where there is malformed data.
surrogateescapewill represent any incorrect bytes as code points in the Unicode Private Use Area ranging from U+DC80 to U+DCFF. These private code points will then be turned back into the same bytes when the surrogateescape error handler is used when writing data. This is useful for processing files in an unknown encoding.
xmlcharrefreplaceis only supported when writing to a file. Characters not supported by the encoding are replaced with the appropriate XML character reference nnn;.
backslashreplacereplaces malformed data by Python’s backslashed escape sequences.
namereplace(also only supported when writing) replaces unsupported characters with \N{...} escape sequences.
- newline controls how universal newlines mode works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:
When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.
When writing output to the stream, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '\n', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string.
- If closefd is False and a file descriptor rather than a filename was given, the underlying file descriptor will be kept open when the file is closed. If a filename is given closefd must be True (the default) otherwise an error will be raised.
- A custom opener can be used by passing a callable as opener. The underlying file descriptor for the file object is then obtained by calling opener with (file, flags). opener must return an open file descriptor (passing os.open as opener results in functionality similar to passing None).
- The newly created file is non-inheritable.
- The type of file object returned by the open() function depends on the mode. When open() is used to open a file in a text mode ('w', 'r', 'wt', 'rt', etc.), it returns a subclass of io.TextIOBase (specifically io.TextIOWrapper). When used to open a file in a binary mode with buffering, the returned class is a subclass of io.BufferedIOBase. The exact class varies: in read binary mode, it returns an io.BufferedReader; in write binary and append binary modes, it returns an io.BufferedWriter, and in read/write mode, it returns an io.BufferedRandom. When buffering is disabled, the raw stream, a subclass of io.RawIOBase, io.FileIO, is returned.
- Raises an auditing event open with arguments file, mode, flags.
- The mode and flags arguments may have been modified or inferred from the original call.
print()
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Parameters
print()to print objects to the text stream file.
*objectsto specify the objects to be printed from
sep=' 'to specify the sep to be used as separator
end='\n'to specify the end to be used as ending
file=sys.stdoutto specify the file to be printed to
flush=Falseto specify whether the buffer is flushed or not
Remarks
- Print objects to the text stream file, separated by sep and followed by end. sep, end, file and flush, if present, must be given as keyword arguments.
All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end. Both sep and end must be strings; they can also be None, which means to use the default values. If no objects are given, print() will just write end.
The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.
Whether output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.
__import__()
__import__(name, globals=None, locals=None, fromlist=(), level=0)
Parameters
__import__()to import the module named by the specified name.
nameto specify the name to be imported.
globals=Noneto specify the globals to be used in interpreting the name in a package context.
locals=Noneto specify the locals to be used in interpreting the name in a package context.
fromlist=()to specify the fromlist of objects or submodules that should be imported from the module given by name
level=0to specify the level whether to use absolute or relative imports
Remarks
-
Note
This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module().
This function is invoked by the import statement. It can be replaced (by importing the builtins module and assigning to builtins.__import__) in order to change semantics of the import statement, but doing so is strongly discouraged as it is usually simpler to use import hooks (see PEP 302) to attain the same goals and does not cause issues with code which assumes the default import implementation is in use. Direct use of __import__() is also discouraged in favor of importlib.import_module().
The function imports the module name, potentially using the given globals and locals to determine how to interpret the name in a package context. The fromlist gives the names of objects or submodules that should be imported from the module given by name. The standard implementation does not use its locals argument at all, and uses its globals only to determine the package context of the import statement.
level specifies whether to use absolute or relative imports. 0 (the default) means only perform absolute imports. Positive values for level indicate the number of parent directories to search relative to the directory of the module calling __import__() (see PEP 328 for the details).
When the name variable is of the form package.module, normally, the top-level package (the name up till the first dot) is returned, not the module named by name. However, when a non-empty fromlist argument is given, the module named by name is returned.
For example, the statement import spam results in bytecode resembling the following code:
spam = __import__('spam', globals(), locals(), [], 0)
The statement import spam.ham results in this call:
spam = __import__('spam.ham', globals(), locals(), [], 0)
Note how __import__() returns the toplevel module here because this is the object that is bound to a name by the import statement.
On the other hand, the statement from spam.ham import eggs, sausage as saus results in
_temp = __import__('spam.ham', globals(), locals(), ['eggs', 'sausage'], 0)
eggs = _temp.eggs
saus = _temp.sausage
Here, the spam.ham module is returned from __import__(). From this object, the names to import are retrieved and assigned to their respective names.
If you simply want to import a module (potentially within a package) by name, use importlib.import_module().
Source and Reference
©sideway
ID: 210200002 Last Updated: 2/2/2021 Revision: 0
|
 |