doc_content stringlengths 1 386k | doc_id stringlengths 5 188 |
|---|---|
XMLReader.setLocale(locale)
Allow an application to set the locale for errors and warnings. SAX parsers are not required to provide localization for errors and warnings; if they cannot support the requested locale, however, they must raise a SAX exception. Applications may request a locale change in the middle of a parse. | python.library.xml.sax.reader#xml.sax.xmlreader.XMLReader.setLocale |
XMLReader.setProperty(propertyname, value)
Set the propertyname to value. If the property is not recognized, SAXNotRecognizedException is raised. If the property or its setting is not supported by the parser, SAXNotSupportedException is raised. | python.library.xml.sax.reader#xml.sax.xmlreader.XMLReader.setProperty |
xmlrpc — XMLRPC server and client modules XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP as a transport. With it, a client can call methods with parameters on a remote server (the server is named by a URI) and get back structured data. xmlrpc is a package that collects server and client modules implementing XML-RPC. The modules are: xmlrpc.client xmlrpc.server | python.library.xmlrpc |
xmlrpc.client — XML-RPC client access Source code: Lib/xmlrpc/client.py XML-RPC is a Remote Procedure Call method that uses XML passed via HTTP(S) as a transport. With it, a client can call methods with parameters on a remote server (the server is named by a URI) and get back structured data. This module supports writing XML-RPC client code; it handles all the details of translating between conformable Python objects and XML on the wire. Warning The xmlrpc.client module is not secure against maliciously constructed data. If you need to parse untrusted or unauthenticated data see XML vulnerabilities. Changed in version 3.5: For HTTPS URIs, xmlrpc.client now performs all the necessary certificate and hostname checks by default.
class xmlrpc.client.ServerProxy(uri, transport=None, encoding=None, verbose=False, allow_none=False, use_datetime=False, use_builtin_types=False, *, headers=(), context=None)
A ServerProxy instance is an object that manages communication with a remote XML-RPC server. The required first argument is a URI (Uniform Resource Indicator), and will normally be the URL of the server. The optional second argument is a transport factory instance; by default it is an internal SafeTransport instance for https: URLs and an internal HTTP Transport instance otherwise. The optional third argument is an encoding, by default UTF-8. The optional fourth argument is a debugging flag. The following parameters govern the use of the returned proxy instance. If allow_none is true, the Python constant None will be translated into XML; the default behaviour is for None to raise a TypeError. This is a commonly-used extension to the XML-RPC specification, but isn’t supported by all clients and servers; see http://ontosys.com/xml-rpc/extensions.php for a description. The use_builtin_types flag can be used to cause date/time values to be presented as datetime.datetime objects and binary data to be presented as bytes objects; this flag is false by default. datetime.datetime, bytes and bytearray objects may be passed to calls. The headers parameter is an optional sequence of HTTP headers to send with each request, expressed as a sequence of 2-tuples representing the header name and value. (e.g. [(‘Header-Name’, ‘value’)]). The obsolete use_datetime flag is similar to use_builtin_types but it applies only to date/time values.
Changed in version 3.3: The use_builtin_types flag was added. Changed in version 3.8: The headers parameter was added. Both the HTTP and HTTPS transports support the URL syntax extension for HTTP Basic Authentication: http://user:pass@host:port/path. The user:pass portion will be base64-encoded as an HTTP ‘Authorization’ header, and sent to the remote server as part of the connection process when invoking an XML-RPC method. You only need to use this if the remote server requires a Basic Authentication user and password. If an HTTPS URL is provided, context may be ssl.SSLContext and configures the SSL settings of the underlying HTTPS connection. The returned instance is a proxy object with methods that can be used to invoke corresponding RPC calls on the remote server. If the remote server supports the introspection API, the proxy can also be used to query the remote server for the methods it supports (service discovery) and fetch other server-associated metadata. Types that are conformable (e.g. that can be marshalled through XML), include the following (and except where noted, they are unmarshalled as the same Python type):
XML-RPC type Python type
boolean bool
int, i1, i2, i4, i8 or biginteger int in range from -2147483648 to 2147483647. Values get the <int> tag.
double or float float. Values get the <double> tag.
string str
array list or tuple containing conformable elements. Arrays are returned as lists.
struct dict. Keys must be strings, values may be any conformable type. Objects of user-defined classes can be passed in; only their __dict__ attribute is transmitted.
dateTime.iso8601 DateTime or datetime.datetime. Returned type depends on values of use_builtin_types and use_datetime flags.
base64 Binary, bytes or bytearray. Returned type depends on the value of the use_builtin_types flag.
nil The None constant. Passing is allowed only if allow_none is true.
bigdecimal decimal.Decimal. Returned type only. This is the full set of data types supported by XML-RPC. Method calls may also raise a special Fault instance, used to signal XML-RPC server errors, or ProtocolError used to signal an error in the HTTP/HTTPS transport layer. Both Fault and ProtocolError derive from a base class called Error. Note that the xmlrpc client module currently does not marshal instances of subclasses of built-in types. When passing strings, characters special to XML such as <, >, and & will be automatically escaped. However, it’s the caller’s responsibility to ensure that the string is free of characters that aren’t allowed in XML, such as the control characters with ASCII values between 0 and 31 (except, of course, tab, newline and carriage return); failing to do this will result in an XML-RPC request that isn’t well-formed XML. If you have to pass arbitrary bytes via XML-RPC, use bytes or bytearray classes or the Binary wrapper class described below. Server is retained as an alias for ServerProxy for backwards compatibility. New code should use ServerProxy. Changed in version 3.5: Added the context argument. Changed in version 3.6: Added support of type tags with prefixes (e.g. ex:nil). Added support of unmarshalling additional types used by Apache XML-RPC implementation for numerics: i1, i2, i8, biginteger, float and bigdecimal. See http://ws.apache.org/xmlrpc/types.html for a description. See also XML-RPC HOWTO
A good description of XML-RPC operation and client software in several languages. Contains pretty much everything an XML-RPC client developer needs to know. XML-RPC Introspection
Describes the XML-RPC protocol extension for introspection. XML-RPC Specification
The official specification. Unofficial XML-RPC Errata
Fredrik Lundh’s “unofficial errata, intended to clarify certain details in the XML-RPC specification, as well as hint at ‘best practices’ to use when designing your own XML-RPC implementations.” ServerProxy Objects A ServerProxy instance has a method corresponding to each remote procedure call accepted by the XML-RPC server. Calling the method performs an RPC, dispatched by both name and argument signature (e.g. the same method name can be overloaded with multiple argument signatures). The RPC finishes by returning a value, which may be either returned data in a conformant type or a Fault or ProtocolError object indicating an error. Servers that support the XML introspection API support some common methods grouped under the reserved system attribute:
ServerProxy.system.listMethods()
This method returns a list of strings, one for each (non-system) method supported by the XML-RPC server.
ServerProxy.system.methodSignature(name)
This method takes one parameter, the name of a method implemented by the XML-RPC server. It returns an array of possible signatures for this method. A signature is an array of types. The first of these types is the return type of the method, the rest are parameters. Because multiple signatures (ie. overloading) is permitted, this method returns a list of signatures rather than a singleton. Signatures themselves are restricted to the top level parameters expected by a method. For instance if a method expects one array of structs as a parameter, and it returns a string, its signature is simply “string, array”. If it expects three integers and returns a string, its signature is “string, int, int, int”. If no signature is defined for the method, a non-array value is returned. In Python this means that the type of the returned value will be something other than list.
ServerProxy.system.methodHelp(name)
This method takes one parameter, the name of a method implemented by the XML-RPC server. It returns a documentation string describing the use of that method. If no such string is available, an empty string is returned. The documentation string may contain HTML markup.
Changed in version 3.5: Instances of ServerProxy support the context manager protocol for closing the underlying transport. A working example follows. The server code: from xmlrpc.server import SimpleXMLRPCServer
def is_even(n):
return n % 2 == 0
server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(is_even, "is_even")
server.serve_forever()
The client code for the preceding server: import xmlrpc.client
with xmlrpc.client.ServerProxy("http://localhost:8000/") as proxy:
print("3 is even: %s" % str(proxy.is_even(3)))
print("100 is even: %s" % str(proxy.is_even(100)))
DateTime Objects
class xmlrpc.client.DateTime
This class may be initialized with seconds since the epoch, a time tuple, an ISO 8601 time/date string, or a datetime.datetime instance. It has the following methods, supported mainly for internal use by the marshalling/unmarshalling code:
decode(string)
Accept a string as the instance’s new time value.
encode(out)
Write the XML-RPC encoding of this DateTime item to the out stream object.
It also supports certain of Python’s built-in operators through rich comparison and __repr__() methods.
A working example follows. The server code: import datetime
from xmlrpc.server import SimpleXMLRPCServer
import xmlrpc.client
def today():
today = datetime.datetime.today()
return xmlrpc.client.DateTime(today)
server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(today, "today")
server.serve_forever()
The client code for the preceding server: import xmlrpc.client
import datetime
proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
today = proxy.today()
# convert the ISO8601 string to a datetime object
converted = datetime.datetime.strptime(today.value, "%Y%m%dT%H:%M:%S")
print("Today: %s" % converted.strftime("%d.%m.%Y, %H:%M"))
Binary Objects
class xmlrpc.client.Binary
This class may be initialized from bytes data (which may include NULs). The primary access to the content of a Binary object is provided by an attribute:
data
The binary data encapsulated by the Binary instance. The data is provided as a bytes object.
Binary objects have the following methods, supported mainly for internal use by the marshalling/unmarshalling code:
decode(bytes)
Accept a base64 bytes object and decode it as the instance’s new data.
encode(out)
Write the XML-RPC base 64 encoding of this binary item to the out stream object. The encoded data will have newlines every 76 characters as per RFC 2045 section 6.8, which was the de facto standard base64 specification when the XML-RPC spec was written.
It also supports certain of Python’s built-in operators through __eq__() and __ne__() methods.
Example usage of the binary objects. We’re going to transfer an image over XMLRPC: from xmlrpc.server import SimpleXMLRPCServer
import xmlrpc.client
def python_logo():
with open("python_logo.jpg", "rb") as handle:
return xmlrpc.client.Binary(handle.read())
server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(python_logo, 'python_logo')
server.serve_forever()
The client gets the image and saves it to a file: import xmlrpc.client
proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
with open("fetched_python_logo.jpg", "wb") as handle:
handle.write(proxy.python_logo().data)
Fault Objects
class xmlrpc.client.Fault
A Fault object encapsulates the content of an XML-RPC fault tag. Fault objects have the following attributes:
faultCode
A string indicating the fault type.
faultString
A string containing a diagnostic message associated with the fault.
In the following example we’re going to intentionally cause a Fault by returning a complex type object. The server code: from xmlrpc.server import SimpleXMLRPCServer
# A marshalling error is going to occur because we're returning a
# complex number
def add(x, y):
return x+y+0j
server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_function(add, 'add')
server.serve_forever()
The client code for the preceding server: import xmlrpc.client
proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
try:
proxy.add(2, 5)
except xmlrpc.client.Fault as err:
print("A fault occurred")
print("Fault code: %d" % err.faultCode)
print("Fault string: %s" % err.faultString)
ProtocolError Objects
class xmlrpc.client.ProtocolError
A ProtocolError object describes a protocol error in the underlying transport layer (such as a 404 ‘not found’ error if the server named by the URI does not exist). It has the following attributes:
url
The URI or URL that triggered the error.
errcode
The error code.
errmsg
The error message or diagnostic string.
headers
A dict containing the headers of the HTTP/HTTPS request that triggered the error.
In the following example we’re going to intentionally cause a ProtocolError by providing an invalid URI: import xmlrpc.client
# create a ServerProxy with a URI that doesn't respond to XMLRPC requests
proxy = xmlrpc.client.ServerProxy("http://google.com/")
try:
proxy.some_method()
except xmlrpc.client.ProtocolError as err:
print("A protocol error occurred")
print("URL: %s" % err.url)
print("HTTP/HTTPS headers: %s" % err.headers)
print("Error code: %d" % err.errcode)
print("Error message: %s" % err.errmsg)
MultiCall Objects The MultiCall object provides a way to encapsulate multiple calls to a remote server into a single request 1.
class xmlrpc.client.MultiCall(server)
Create an object used to boxcar method calls. server is the eventual target of the call. Calls can be made to the result object, but they will immediately return None, and only store the call name and parameters in the MultiCall object. Calling the object itself causes all stored calls to be transmitted as a single system.multicall request. The result of this call is a generator; iterating over this generator yields the individual results.
A usage example of this class follows. The server code: from xmlrpc.server import SimpleXMLRPCServer
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
return x // y
# A simple server with simple arithmetic functions
server = SimpleXMLRPCServer(("localhost", 8000))
print("Listening on port 8000...")
server.register_multicall_functions()
server.register_function(add, 'add')
server.register_function(subtract, 'subtract')
server.register_function(multiply, 'multiply')
server.register_function(divide, 'divide')
server.serve_forever()
The client code for the preceding server: import xmlrpc.client
proxy = xmlrpc.client.ServerProxy("http://localhost:8000/")
multicall = xmlrpc.client.MultiCall(proxy)
multicall.add(7, 3)
multicall.subtract(7, 3)
multicall.multiply(7, 3)
multicall.divide(7, 3)
result = multicall()
print("7+3=%d, 7-3=%d, 7*3=%d, 7//3=%d" % tuple(result))
Convenience Functions
xmlrpc.client.dumps(params, methodname=None, methodresponse=None, encoding=None, allow_none=False)
Convert params into an XML-RPC request. or into a response if methodresponse is true. params can be either a tuple of arguments or an instance of the Fault exception class. If methodresponse is true, only a single value can be returned, meaning that params must be of length 1. encoding, if supplied, is the encoding to use in the generated XML; the default is UTF-8. Python’s None value cannot be used in standard XML-RPC; to allow using it via an extension, provide a true value for allow_none.
xmlrpc.client.loads(data, use_datetime=False, use_builtin_types=False)
Convert an XML-RPC request or response into Python objects, a (params,
methodname). params is a tuple of argument; methodname is a string, or None if no method name is present in the packet. If the XML-RPC packet represents a fault condition, this function will raise a Fault exception. The use_builtin_types flag can be used to cause date/time values to be presented as datetime.datetime objects and binary data to be presented as bytes objects; this flag is false by default. The obsolete use_datetime flag is similar to use_builtin_types but it applies only to date/time values. Changed in version 3.3: The use_builtin_types flag was added.
Example of Client Usage # simple test program (from the XML-RPC specification)
from xmlrpc.client import ServerProxy, Error
# server = ServerProxy("http://localhost:8000") # local server
with ServerProxy("http://betty.userland.com") as proxy:
print(proxy)
try:
print(proxy.examples.getStateName(41))
except Error as v:
print("ERROR", v)
To access an XML-RPC server through a HTTP proxy, you need to define a custom transport. The following example shows how: import http.client
import xmlrpc.client
class ProxiedTransport(xmlrpc.client.Transport):
def set_proxy(self, host, port=None, headers=None):
self.proxy = host, port
self.proxy_headers = headers
def make_connection(self, host):
connection = http.client.HTTPConnection(*self.proxy)
connection.set_tunnel(host, headers=self.proxy_headers)
self._connection = host, connection
return connection
transport = ProxiedTransport()
transport.set_proxy('proxy-server', 8080)
server = xmlrpc.client.ServerProxy('http://betty.userland.com', transport=transport)
print(server.examples.getStateName(41))
Example of Client and Server Usage See SimpleXMLRPCServer Example. Footnotes
1
This approach has been first presented in a discussion on xmlrpc.com. | python.library.xmlrpc.client |
class xmlrpc.client.Binary
This class may be initialized from bytes data (which may include NULs). The primary access to the content of a Binary object is provided by an attribute:
data
The binary data encapsulated by the Binary instance. The data is provided as a bytes object.
Binary objects have the following methods, supported mainly for internal use by the marshalling/unmarshalling code:
decode(bytes)
Accept a base64 bytes object and decode it as the instance’s new data.
encode(out)
Write the XML-RPC base 64 encoding of this binary item to the out stream object. The encoded data will have newlines every 76 characters as per RFC 2045 section 6.8, which was the de facto standard base64 specification when the XML-RPC spec was written.
It also supports certain of Python’s built-in operators through __eq__() and __ne__() methods. | python.library.xmlrpc.client#xmlrpc.client.Binary |
data
The binary data encapsulated by the Binary instance. The data is provided as a bytes object. | python.library.xmlrpc.client#xmlrpc.client.Binary.data |
decode(bytes)
Accept a base64 bytes object and decode it as the instance’s new data. | python.library.xmlrpc.client#xmlrpc.client.Binary.decode |
encode(out)
Write the XML-RPC base 64 encoding of this binary item to the out stream object. The encoded data will have newlines every 76 characters as per RFC 2045 section 6.8, which was the de facto standard base64 specification when the XML-RPC spec was written. | python.library.xmlrpc.client#xmlrpc.client.Binary.encode |
class xmlrpc.client.DateTime
This class may be initialized with seconds since the epoch, a time tuple, an ISO 8601 time/date string, or a datetime.datetime instance. It has the following methods, supported mainly for internal use by the marshalling/unmarshalling code:
decode(string)
Accept a string as the instance’s new time value.
encode(out)
Write the XML-RPC encoding of this DateTime item to the out stream object.
It also supports certain of Python’s built-in operators through rich comparison and __repr__() methods. | python.library.xmlrpc.client#xmlrpc.client.DateTime |
decode(string)
Accept a string as the instance’s new time value. | python.library.xmlrpc.client#xmlrpc.client.DateTime.decode |
encode(out)
Write the XML-RPC encoding of this DateTime item to the out stream object. | python.library.xmlrpc.client#xmlrpc.client.DateTime.encode |
xmlrpc.client.dumps(params, methodname=None, methodresponse=None, encoding=None, allow_none=False)
Convert params into an XML-RPC request. or into a response if methodresponse is true. params can be either a tuple of arguments or an instance of the Fault exception class. If methodresponse is true, only a single value can be returned, meaning that params must be of length 1. encoding, if supplied, is the encoding to use in the generated XML; the default is UTF-8. Python’s None value cannot be used in standard XML-RPC; to allow using it via an extension, provide a true value for allow_none. | python.library.xmlrpc.client#xmlrpc.client.dumps |
class xmlrpc.client.Fault
A Fault object encapsulates the content of an XML-RPC fault tag. Fault objects have the following attributes:
faultCode
A string indicating the fault type.
faultString
A string containing a diagnostic message associated with the fault. | python.library.xmlrpc.client#xmlrpc.client.Fault |
faultCode
A string indicating the fault type. | python.library.xmlrpc.client#xmlrpc.client.Fault.faultCode |
faultString
A string containing a diagnostic message associated with the fault. | python.library.xmlrpc.client#xmlrpc.client.Fault.faultString |
xmlrpc.client.loads(data, use_datetime=False, use_builtin_types=False)
Convert an XML-RPC request or response into Python objects, a (params,
methodname). params is a tuple of argument; methodname is a string, or None if no method name is present in the packet. If the XML-RPC packet represents a fault condition, this function will raise a Fault exception. The use_builtin_types flag can be used to cause date/time values to be presented as datetime.datetime objects and binary data to be presented as bytes objects; this flag is false by default. The obsolete use_datetime flag is similar to use_builtin_types but it applies only to date/time values. Changed in version 3.3: The use_builtin_types flag was added. | python.library.xmlrpc.client#xmlrpc.client.loads |
class xmlrpc.client.MultiCall(server)
Create an object used to boxcar method calls. server is the eventual target of the call. Calls can be made to the result object, but they will immediately return None, and only store the call name and parameters in the MultiCall object. Calling the object itself causes all stored calls to be transmitted as a single system.multicall request. The result of this call is a generator; iterating over this generator yields the individual results. | python.library.xmlrpc.client#xmlrpc.client.MultiCall |
class xmlrpc.client.ProtocolError
A ProtocolError object describes a protocol error in the underlying transport layer (such as a 404 ‘not found’ error if the server named by the URI does not exist). It has the following attributes:
url
The URI or URL that triggered the error.
errcode
The error code.
errmsg
The error message or diagnostic string.
headers
A dict containing the headers of the HTTP/HTTPS request that triggered the error. | python.library.xmlrpc.client#xmlrpc.client.ProtocolError |
errcode
The error code. | python.library.xmlrpc.client#xmlrpc.client.ProtocolError.errcode |
errmsg
The error message or diagnostic string. | python.library.xmlrpc.client#xmlrpc.client.ProtocolError.errmsg |
headers
A dict containing the headers of the HTTP/HTTPS request that triggered the error. | python.library.xmlrpc.client#xmlrpc.client.ProtocolError.headers |
url
The URI or URL that triggered the error. | python.library.xmlrpc.client#xmlrpc.client.ProtocolError.url |
class xmlrpc.client.ServerProxy(uri, transport=None, encoding=None, verbose=False, allow_none=False, use_datetime=False, use_builtin_types=False, *, headers=(), context=None)
A ServerProxy instance is an object that manages communication with a remote XML-RPC server. The required first argument is a URI (Uniform Resource Indicator), and will normally be the URL of the server. The optional second argument is a transport factory instance; by default it is an internal SafeTransport instance for https: URLs and an internal HTTP Transport instance otherwise. The optional third argument is an encoding, by default UTF-8. The optional fourth argument is a debugging flag. The following parameters govern the use of the returned proxy instance. If allow_none is true, the Python constant None will be translated into XML; the default behaviour is for None to raise a TypeError. This is a commonly-used extension to the XML-RPC specification, but isn’t supported by all clients and servers; see http://ontosys.com/xml-rpc/extensions.php for a description. The use_builtin_types flag can be used to cause date/time values to be presented as datetime.datetime objects and binary data to be presented as bytes objects; this flag is false by default. datetime.datetime, bytes and bytearray objects may be passed to calls. The headers parameter is an optional sequence of HTTP headers to send with each request, expressed as a sequence of 2-tuples representing the header name and value. (e.g. [(‘Header-Name’, ‘value’)]). The obsolete use_datetime flag is similar to use_builtin_types but it applies only to date/time values. | python.library.xmlrpc.client#xmlrpc.client.ServerProxy |
ServerProxy.system.listMethods()
This method returns a list of strings, one for each (non-system) method supported by the XML-RPC server. | python.library.xmlrpc.client#xmlrpc.client.ServerProxy.system.listMethods |
ServerProxy.system.methodHelp(name)
This method takes one parameter, the name of a method implemented by the XML-RPC server. It returns a documentation string describing the use of that method. If no such string is available, an empty string is returned. The documentation string may contain HTML markup. | python.library.xmlrpc.client#xmlrpc.client.ServerProxy.system.methodHelp |
ServerProxy.system.methodSignature(name)
This method takes one parameter, the name of a method implemented by the XML-RPC server. It returns an array of possible signatures for this method. A signature is an array of types. The first of these types is the return type of the method, the rest are parameters. Because multiple signatures (ie. overloading) is permitted, this method returns a list of signatures rather than a singleton. Signatures themselves are restricted to the top level parameters expected by a method. For instance if a method expects one array of structs as a parameter, and it returns a string, its signature is simply “string, array”. If it expects three integers and returns a string, its signature is “string, int, int, int”. If no signature is defined for the method, a non-array value is returned. In Python this means that the type of the returned value will be something other than list. | python.library.xmlrpc.client#xmlrpc.client.ServerProxy.system.methodSignature |
xmlrpc.server — Basic XML-RPC servers Source code: Lib/xmlrpc/server.py The xmlrpc.server module provides a basic server framework for XML-RPC servers written in Python. Servers can either be free standing, using SimpleXMLRPCServer, or embedded in a CGI environment, using CGIXMLRPCRequestHandler. Warning The xmlrpc.server module is not secure against maliciously constructed data. If you need to parse untrusted or unauthenticated data see XML vulnerabilities.
class xmlrpc.server.SimpleXMLRPCServer(addr, requestHandler=SimpleXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True, use_builtin_types=False)
Create a new server instance. This class provides methods for registration of functions that can be called by the XML-RPC protocol. The requestHandler parameter should be a factory for request handler instances; it defaults to SimpleXMLRPCRequestHandler. The addr and requestHandler parameters are passed to the socketserver.TCPServer constructor. If logRequests is true (the default), requests will be logged; setting this parameter to false will turn off logging. The allow_none and encoding parameters are passed on to xmlrpc.client and control the XML-RPC responses that will be returned from the server. The bind_and_activate parameter controls whether server_bind() and server_activate() are called immediately by the constructor; it defaults to true. Setting it to false allows code to manipulate the allow_reuse_address class variable before the address is bound. The use_builtin_types parameter is passed to the loads() function and controls which types are processed when date/times values or binary data are received; it defaults to false. Changed in version 3.3: The use_builtin_types flag was added.
class xmlrpc.server.CGIXMLRPCRequestHandler(allow_none=False, encoding=None, use_builtin_types=False)
Create a new instance to handle XML-RPC requests in a CGI environment. The allow_none and encoding parameters are passed on to xmlrpc.client and control the XML-RPC responses that will be returned from the server. The use_builtin_types parameter is passed to the loads() function and controls which types are processed when date/times values or binary data are received; it defaults to false. Changed in version 3.3: The use_builtin_types flag was added.
class xmlrpc.server.SimpleXMLRPCRequestHandler
Create a new request handler instance. This request handler supports POST requests and modifies logging so that the logRequests parameter to the SimpleXMLRPCServer constructor parameter is honored.
SimpleXMLRPCServer Objects The SimpleXMLRPCServer class is based on socketserver.TCPServer and provides a means of creating simple, stand alone XML-RPC servers.
SimpleXMLRPCServer.register_function(function=None, name=None)
Register a function that can respond to XML-RPC requests. If name is given, it will be the method name associated with function, otherwise function.__name__ will be used. name is a string, and may contain characters not legal in Python identifiers, including the period character. This method can also be used as a decorator. When used as a decorator, name can only be given as a keyword argument to register function under name. If no name is given, function.__name__ will be used. Changed in version 3.7: register_function() can be used as a decorator.
SimpleXMLRPCServer.register_instance(instance, allow_dotted_names=False)
Register an object which is used to expose method names which have not been registered using register_function(). If instance contains a _dispatch() method, it is called with the requested method name and the parameters from the request. Its API is def _dispatch(self, method, params) (note that params does not represent a variable argument list). If it calls an underlying function to perform its task, that function is called as func(*params), expanding the parameter list. The return value from _dispatch() is returned to the client as the result. If instance does not have a _dispatch() method, it is searched for an attribute matching the name of the requested method. If the optional allow_dotted_names argument is true and the instance does not have a _dispatch() method, then if the requested method name contains periods, each component of the method name is searched for individually, with the effect that a simple hierarchical search is performed. The value found from this search is then called with the parameters from the request, and the return value is passed back to the client. Warning Enabling the allow_dotted_names option allows intruders to access your module’s global variables and may allow intruders to execute arbitrary code on your machine. Only use this option on a secure, closed network.
SimpleXMLRPCServer.register_introspection_functions()
Registers the XML-RPC introspection functions system.listMethods, system.methodHelp and system.methodSignature.
SimpleXMLRPCServer.register_multicall_functions()
Registers the XML-RPC multicall function system.multicall.
SimpleXMLRPCRequestHandler.rpc_paths
An attribute value that must be a tuple listing valid path portions of the URL for receiving XML-RPC requests. Requests posted to other paths will result in a 404 “no such page” HTTP error. If this tuple is empty, all paths will be considered valid. The default value is ('/', '/RPC2').
SimpleXMLRPCServer Example Server code: from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler
# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
# Create server
with SimpleXMLRPCServer(('localhost', 8000),
requestHandler=RequestHandler) as server:
server.register_introspection_functions()
# Register pow() function; this will use the value of
# pow.__name__ as the name, which is just 'pow'.
server.register_function(pow)
# Register a function under a different name
def adder_function(x, y):
return x + y
server.register_function(adder_function, 'add')
# Register an instance; all the methods of the instance are
# published as XML-RPC methods (in this case, just 'mul').
class MyFuncs:
def mul(self, x, y):
return x * y
server.register_instance(MyFuncs())
# Run the server's main loop
server.serve_forever()
The following client code will call the methods made available by the preceding server: import xmlrpc.client
s = xmlrpc.client.ServerProxy('http://localhost:8000')
print(s.pow(2,3)) # Returns 2**3 = 8
print(s.add(2,3)) # Returns 5
print(s.mul(5,2)) # Returns 5*2 = 10
# Print list of available methods
print(s.system.listMethods())
register_function() can also be used as a decorator. The previous server example can register functions in a decorator way: from xmlrpc.server import SimpleXMLRPCServer
from xmlrpc.server import SimpleXMLRPCRequestHandler
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
with SimpleXMLRPCServer(('localhost', 8000),
requestHandler=RequestHandler) as server:
server.register_introspection_functions()
# Register pow() function; this will use the value of
# pow.__name__ as the name, which is just 'pow'.
server.register_function(pow)
# Register a function under a different name, using
# register_function as a decorator. *name* can only be given
# as a keyword argument.
@server.register_function(name='add')
def adder_function(x, y):
return x + y
# Register a function under function.__name__.
@server.register_function
def mul(x, y):
return x * y
server.serve_forever()
The following example included in the Lib/xmlrpc/server.py module shows a server allowing dotted names and registering a multicall function. Warning Enabling the allow_dotted_names option allows intruders to access your module’s global variables and may allow intruders to execute arbitrary code on your machine. Only use this example only within a secure, closed network. import datetime
class ExampleService:
def getData(self):
return '42'
class currentTime:
@staticmethod
def getCurrentTime():
return datetime.datetime.now()
with SimpleXMLRPCServer(("localhost", 8000)) as server:
server.register_function(pow)
server.register_function(lambda x,y: x+y, 'add')
server.register_instance(ExampleService(), allow_dotted_names=True)
server.register_multicall_functions()
print('Serving XML-RPC on localhost port 8000')
try:
server.serve_forever()
except KeyboardInterrupt:
print("\nKeyboard interrupt received, exiting.")
sys.exit(0)
This ExampleService demo can be invoked from the command line: python -m xmlrpc.server
The client that interacts with the above server is included in Lib/xmlrpc/client.py: server = ServerProxy("http://localhost:8000")
try:
print(server.currentTime.getCurrentTime())
except Error as v:
print("ERROR", v)
multi = MultiCall(server)
multi.getData()
multi.pow(2,9)
multi.add(1,2)
try:
for response in multi():
print(response)
except Error as v:
print("ERROR", v)
This client which interacts with the demo XMLRPC server can be invoked as: python -m xmlrpc.client
CGIXMLRPCRequestHandler The CGIXMLRPCRequestHandler class can be used to handle XML-RPC requests sent to Python CGI scripts.
CGIXMLRPCRequestHandler.register_function(function=None, name=None)
Register a function that can respond to XML-RPC requests. If name is given, it will be the method name associated with function, otherwise function.__name__ will be used. name is a string, and may contain characters not legal in Python identifiers, including the period character. This method can also be used as a decorator. When used as a decorator, name can only be given as a keyword argument to register function under name. If no name is given, function.__name__ will be used. Changed in version 3.7: register_function() can be used as a decorator.
CGIXMLRPCRequestHandler.register_instance(instance)
Register an object which is used to expose method names which have not been registered using register_function(). If instance contains a _dispatch() method, it is called with the requested method name and the parameters from the request; the return value is returned to the client as the result. If instance does not have a _dispatch() method, it is searched for an attribute matching the name of the requested method; if the requested method name contains periods, each component of the method name is searched for individually, with the effect that a simple hierarchical search is performed. The value found from this search is then called with the parameters from the request, and the return value is passed back to the client.
CGIXMLRPCRequestHandler.register_introspection_functions()
Register the XML-RPC introspection functions system.listMethods, system.methodHelp and system.methodSignature.
CGIXMLRPCRequestHandler.register_multicall_functions()
Register the XML-RPC multicall function system.multicall.
CGIXMLRPCRequestHandler.handle_request(request_text=None)
Handle an XML-RPC request. If request_text is given, it should be the POST data provided by the HTTP server, otherwise the contents of stdin will be used.
Example: class MyFuncs:
def mul(self, x, y):
return x * y
handler = CGIXMLRPCRequestHandler()
handler.register_function(pow)
handler.register_function(lambda x,y: x+y, 'add')
handler.register_introspection_functions()
handler.register_instance(MyFuncs())
handler.handle_request()
Documenting XMLRPC server These classes extend the above classes to serve HTML documentation in response to HTTP GET requests. Servers can either be free standing, using DocXMLRPCServer, or embedded in a CGI environment, using DocCGIXMLRPCRequestHandler.
class xmlrpc.server.DocXMLRPCServer(addr, requestHandler=DocXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True, use_builtin_types=True)
Create a new server instance. All parameters have the same meaning as for SimpleXMLRPCServer; requestHandler defaults to DocXMLRPCRequestHandler. Changed in version 3.3: The use_builtin_types flag was added.
class xmlrpc.server.DocCGIXMLRPCRequestHandler
Create a new instance to handle XML-RPC requests in a CGI environment.
class xmlrpc.server.DocXMLRPCRequestHandler
Create a new request handler instance. This request handler supports XML-RPC POST requests, documentation GET requests, and modifies logging so that the logRequests parameter to the DocXMLRPCServer constructor parameter is honored.
DocXMLRPCServer Objects The DocXMLRPCServer class is derived from SimpleXMLRPCServer and provides a means of creating self-documenting, stand alone XML-RPC servers. HTTP POST requests are handled as XML-RPC method calls. HTTP GET requests are handled by generating pydoc-style HTML documentation. This allows a server to provide its own web-based documentation.
DocXMLRPCServer.set_server_title(server_title)
Set the title used in the generated HTML documentation. This title will be used inside the HTML “title” element.
DocXMLRPCServer.set_server_name(server_name)
Set the name used in the generated HTML documentation. This name will appear at the top of the generated documentation inside a “h1” element.
DocXMLRPCServer.set_server_documentation(server_documentation)
Set the description used in the generated HTML documentation. This description will appear as a paragraph, below the server name, in the documentation.
DocCGIXMLRPCRequestHandler The DocCGIXMLRPCRequestHandler class is derived from CGIXMLRPCRequestHandler and provides a means of creating self-documenting, XML-RPC CGI scripts. HTTP POST requests are handled as XML-RPC method calls. HTTP GET requests are handled by generating pydoc-style HTML documentation. This allows a server to provide its own web-based documentation.
DocCGIXMLRPCRequestHandler.set_server_title(server_title)
Set the title used in the generated HTML documentation. This title will be used inside the HTML “title” element.
DocCGIXMLRPCRequestHandler.set_server_name(server_name)
Set the name used in the generated HTML documentation. This name will appear at the top of the generated documentation inside a “h1” element.
DocCGIXMLRPCRequestHandler.set_server_documentation(server_documentation)
Set the description used in the generated HTML documentation. This description will appear as a paragraph, below the server name, in the documentation. | python.library.xmlrpc.server |
class xmlrpc.server.CGIXMLRPCRequestHandler(allow_none=False, encoding=None, use_builtin_types=False)
Create a new instance to handle XML-RPC requests in a CGI environment. The allow_none and encoding parameters are passed on to xmlrpc.client and control the XML-RPC responses that will be returned from the server. The use_builtin_types parameter is passed to the loads() function and controls which types are processed when date/times values or binary data are received; it defaults to false. Changed in version 3.3: The use_builtin_types flag was added. | python.library.xmlrpc.server#xmlrpc.server.CGIXMLRPCRequestHandler |
CGIXMLRPCRequestHandler.handle_request(request_text=None)
Handle an XML-RPC request. If request_text is given, it should be the POST data provided by the HTTP server, otherwise the contents of stdin will be used. | python.library.xmlrpc.server#xmlrpc.server.CGIXMLRPCRequestHandler.handle_request |
CGIXMLRPCRequestHandler.register_function(function=None, name=None)
Register a function that can respond to XML-RPC requests. If name is given, it will be the method name associated with function, otherwise function.__name__ will be used. name is a string, and may contain characters not legal in Python identifiers, including the period character. This method can also be used as a decorator. When used as a decorator, name can only be given as a keyword argument to register function under name. If no name is given, function.__name__ will be used. Changed in version 3.7: register_function() can be used as a decorator. | python.library.xmlrpc.server#xmlrpc.server.CGIXMLRPCRequestHandler.register_function |
CGIXMLRPCRequestHandler.register_instance(instance)
Register an object which is used to expose method names which have not been registered using register_function(). If instance contains a _dispatch() method, it is called with the requested method name and the parameters from the request; the return value is returned to the client as the result. If instance does not have a _dispatch() method, it is searched for an attribute matching the name of the requested method; if the requested method name contains periods, each component of the method name is searched for individually, with the effect that a simple hierarchical search is performed. The value found from this search is then called with the parameters from the request, and the return value is passed back to the client. | python.library.xmlrpc.server#xmlrpc.server.CGIXMLRPCRequestHandler.register_instance |
CGIXMLRPCRequestHandler.register_introspection_functions()
Register the XML-RPC introspection functions system.listMethods, system.methodHelp and system.methodSignature. | python.library.xmlrpc.server#xmlrpc.server.CGIXMLRPCRequestHandler.register_introspection_functions |
CGIXMLRPCRequestHandler.register_multicall_functions()
Register the XML-RPC multicall function system.multicall. | python.library.xmlrpc.server#xmlrpc.server.CGIXMLRPCRequestHandler.register_multicall_functions |
class xmlrpc.server.DocCGIXMLRPCRequestHandler
Create a new instance to handle XML-RPC requests in a CGI environment. | python.library.xmlrpc.server#xmlrpc.server.DocCGIXMLRPCRequestHandler |
DocCGIXMLRPCRequestHandler.set_server_documentation(server_documentation)
Set the description used in the generated HTML documentation. This description will appear as a paragraph, below the server name, in the documentation. | python.library.xmlrpc.server#xmlrpc.server.DocCGIXMLRPCRequestHandler.set_server_documentation |
DocCGIXMLRPCRequestHandler.set_server_name(server_name)
Set the name used in the generated HTML documentation. This name will appear at the top of the generated documentation inside a “h1” element. | python.library.xmlrpc.server#xmlrpc.server.DocCGIXMLRPCRequestHandler.set_server_name |
DocCGIXMLRPCRequestHandler.set_server_title(server_title)
Set the title used in the generated HTML documentation. This title will be used inside the HTML “title” element. | python.library.xmlrpc.server#xmlrpc.server.DocCGIXMLRPCRequestHandler.set_server_title |
class xmlrpc.server.DocXMLRPCRequestHandler
Create a new request handler instance. This request handler supports XML-RPC POST requests, documentation GET requests, and modifies logging so that the logRequests parameter to the DocXMLRPCServer constructor parameter is honored. | python.library.xmlrpc.server#xmlrpc.server.DocXMLRPCRequestHandler |
class xmlrpc.server.DocXMLRPCServer(addr, requestHandler=DocXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True, use_builtin_types=True)
Create a new server instance. All parameters have the same meaning as for SimpleXMLRPCServer; requestHandler defaults to DocXMLRPCRequestHandler. Changed in version 3.3: The use_builtin_types flag was added. | python.library.xmlrpc.server#xmlrpc.server.DocXMLRPCServer |
DocXMLRPCServer.set_server_documentation(server_documentation)
Set the description used in the generated HTML documentation. This description will appear as a paragraph, below the server name, in the documentation. | python.library.xmlrpc.server#xmlrpc.server.DocXMLRPCServer.set_server_documentation |
DocXMLRPCServer.set_server_name(server_name)
Set the name used in the generated HTML documentation. This name will appear at the top of the generated documentation inside a “h1” element. | python.library.xmlrpc.server#xmlrpc.server.DocXMLRPCServer.set_server_name |
DocXMLRPCServer.set_server_title(server_title)
Set the title used in the generated HTML documentation. This title will be used inside the HTML “title” element. | python.library.xmlrpc.server#xmlrpc.server.DocXMLRPCServer.set_server_title |
class xmlrpc.server.SimpleXMLRPCRequestHandler
Create a new request handler instance. This request handler supports POST requests and modifies logging so that the logRequests parameter to the SimpleXMLRPCServer constructor parameter is honored. | python.library.xmlrpc.server#xmlrpc.server.SimpleXMLRPCRequestHandler |
SimpleXMLRPCRequestHandler.rpc_paths
An attribute value that must be a tuple listing valid path portions of the URL for receiving XML-RPC requests. Requests posted to other paths will result in a 404 “no such page” HTTP error. If this tuple is empty, all paths will be considered valid. The default value is ('/', '/RPC2'). | python.library.xmlrpc.server#xmlrpc.server.SimpleXMLRPCRequestHandler.rpc_paths |
class xmlrpc.server.SimpleXMLRPCServer(addr, requestHandler=SimpleXMLRPCRequestHandler, logRequests=True, allow_none=False, encoding=None, bind_and_activate=True, use_builtin_types=False)
Create a new server instance. This class provides methods for registration of functions that can be called by the XML-RPC protocol. The requestHandler parameter should be a factory for request handler instances; it defaults to SimpleXMLRPCRequestHandler. The addr and requestHandler parameters are passed to the socketserver.TCPServer constructor. If logRequests is true (the default), requests will be logged; setting this parameter to false will turn off logging. The allow_none and encoding parameters are passed on to xmlrpc.client and control the XML-RPC responses that will be returned from the server. The bind_and_activate parameter controls whether server_bind() and server_activate() are called immediately by the constructor; it defaults to true. Setting it to false allows code to manipulate the allow_reuse_address class variable before the address is bound. The use_builtin_types parameter is passed to the loads() function and controls which types are processed when date/times values or binary data are received; it defaults to false. Changed in version 3.3: The use_builtin_types flag was added. | python.library.xmlrpc.server#xmlrpc.server.SimpleXMLRPCServer |
SimpleXMLRPCServer.register_function(function=None, name=None)
Register a function that can respond to XML-RPC requests. If name is given, it will be the method name associated with function, otherwise function.__name__ will be used. name is a string, and may contain characters not legal in Python identifiers, including the period character. This method can also be used as a decorator. When used as a decorator, name can only be given as a keyword argument to register function under name. If no name is given, function.__name__ will be used. Changed in version 3.7: register_function() can be used as a decorator. | python.library.xmlrpc.server#xmlrpc.server.SimpleXMLRPCServer.register_function |
SimpleXMLRPCServer.register_instance(instance, allow_dotted_names=False)
Register an object which is used to expose method names which have not been registered using register_function(). If instance contains a _dispatch() method, it is called with the requested method name and the parameters from the request. Its API is def _dispatch(self, method, params) (note that params does not represent a variable argument list). If it calls an underlying function to perform its task, that function is called as func(*params), expanding the parameter list. The return value from _dispatch() is returned to the client as the result. If instance does not have a _dispatch() method, it is searched for an attribute matching the name of the requested method. If the optional allow_dotted_names argument is true and the instance does not have a _dispatch() method, then if the requested method name contains periods, each component of the method name is searched for individually, with the effect that a simple hierarchical search is performed. The value found from this search is then called with the parameters from the request, and the return value is passed back to the client. Warning Enabling the allow_dotted_names option allows intruders to access your module’s global variables and may allow intruders to execute arbitrary code on your machine. Only use this option on a secure, closed network. | python.library.xmlrpc.server#xmlrpc.server.SimpleXMLRPCServer.register_instance |
SimpleXMLRPCServer.register_introspection_functions()
Registers the XML-RPC introspection functions system.listMethods, system.methodHelp and system.methodSignature. | python.library.xmlrpc.server#xmlrpc.server.SimpleXMLRPCServer.register_introspection_functions |
SimpleXMLRPCServer.register_multicall_functions()
Registers the XML-RPC multicall function system.multicall. | python.library.xmlrpc.server#xmlrpc.server.SimpleXMLRPCServer.register_multicall_functions |
exception ZeroDivisionError
Raised when the second argument of a division or modulo operation is zero. The associated value is a string indicating the type of the operands and the operation. | python.library.exceptions#ZeroDivisionError |
zip(*iterables)
Make an iterator that aggregates elements from each of the iterables. Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator. Equivalent to: def zip(*iterables):
# zip('ABCD', 'xy') --> Ax By
sentinel = object()
iterators = [iter(it) for it in iterables]
while iterators:
result = []
for it in iterators:
elem = next(it, sentinel)
if elem is sentinel:
return
result.append(elem)
yield tuple(result)
The left-to-right evaluation order of the iterables is guaranteed. This makes possible an idiom for clustering a data series into n-length groups using zip(*[iter(s)]*n). This repeats the same iterator n times so that each output tuple has the result of n calls to the iterator. This has the effect of dividing the input into n-length chunks. zip() should only be used with unequal length inputs when you don’t care about trailing, unmatched values from the longer iterables. If those values are important, use itertools.zip_longest() instead. zip() in conjunction with the * operator can be used to unzip a list: >>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> list(zipped)
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zip(x, y))
>>> x == list(x2) and y == list(y2)
True | python.library.functions#zip |
zipapp — Manage executable Python zip archives New in version 3.5. Source code: Lib/zipapp.py This module provides tools to manage the creation of zip files containing Python code, which can be executed directly by the Python interpreter. The module provides both a Command-Line Interface and a Python API. Basic Example The following example shows how the Command-Line Interface can be used to create an executable archive from a directory containing Python code. When run, the archive will execute the main function from the module myapp in the archive. $ python -m zipapp myapp -m "myapp:main"
$ python myapp.pyz
<output from myapp>
Command-Line Interface When called as a program from the command line, the following form is used: $ python -m zipapp source [options]
If source is a directory, this will create an archive from the contents of source. If source is a file, it should be an archive, and it will be copied to the target archive (or the contents of its shebang line will be displayed if the –info option is specified). The following options are understood:
-o <output>, --output=<output>
Write the output to a file named output. If this option is not specified, the output filename will be the same as the input source, with the extension .pyz added. If an explicit filename is given, it is used as is (so a .pyz extension should be included if required). An output filename must be specified if the source is an archive (and in that case, output must not be the same as source).
-p <interpreter>, --python=<interpreter>
Add a #! line to the archive specifying interpreter as the command to run. Also, on POSIX, make the archive executable. The default is to write no #! line, and not make the file executable.
-m <mainfn>, --main=<mainfn>
Write a __main__.py file to the archive that executes mainfn. The mainfn argument should have the form “pkg.mod:fn”, where “pkg.mod” is a package/module in the archive, and “fn” is a callable in the given module. The __main__.py file will execute that callable. --main cannot be specified when copying an archive.
-c, --compress
Compress files with the deflate method, reducing the size of the output file. By default, files are stored uncompressed in the archive. --compress has no effect when copying an archive. New in version 3.7.
--info
Display the interpreter embedded in the archive, for diagnostic purposes. In this case, any other options are ignored and SOURCE must be an archive, not a directory.
-h, --help
Print a short usage message and exit.
Python API The module defines two convenience functions:
zipapp.create_archive(source, target=None, interpreter=None, main=None, filter=None, compressed=False)
Create an application archive from source. The source can be any of the following: The name of a directory, or a path-like object referring to a directory, in which case a new application archive will be created from the content of that directory. The name of an existing application archive file, or a path-like object referring to such a file, in which case the file is copied to the target (modifying it to reflect the value given for the interpreter argument). The file name should include the .pyz extension, if required. A file object open for reading in bytes mode. The content of the file should be an application archive, and the file object is assumed to be positioned at the start of the archive. The target argument determines where the resulting archive will be written: If it is the name of a file, or a path-like object, the archive will be written to that file. If it is an open file object, the archive will be written to that file object, which must be open for writing in bytes mode. If the target is omitted (or None), the source must be a directory and the target will be a file with the same name as the source, with a .pyz extension added. The interpreter argument specifies the name of the Python interpreter with which the archive will be executed. It is written as a “shebang” line at the start of the archive. On POSIX, this will be interpreted by the OS, and on Windows it will be handled by the Python launcher. Omitting the interpreter results in no shebang line being written. If an interpreter is specified, and the target is a filename, the executable bit of the target file will be set. The main argument specifies the name of a callable which will be used as the main program for the archive. It can only be specified if the source is a directory, and the source does not already contain a __main__.py file. The main argument should take the form “pkg.module:callable” and the archive will be run by importing “pkg.module” and executing the given callable with no arguments. It is an error to omit main if the source is a directory and does not contain a __main__.py file, as otherwise the resulting archive would not be executable. The optional filter argument specifies a callback function that is passed a Path object representing the path to the file being added (relative to the source directory). It should return True if the file is to be added. The optional compressed argument determines whether files are compressed. If set to True, files in the archive are compressed with the deflate method; otherwise, files are stored uncompressed. This argument has no effect when copying an existing archive. If a file object is specified for source or target, it is the caller’s responsibility to close it after calling create_archive. When copying an existing archive, file objects supplied only need read and readline, or write methods. When creating an archive from a directory, if the target is a file object it will be passed to the zipfile.ZipFile class, and must supply the methods needed by that class. New in version 3.7: Added the filter and compressed arguments.
zipapp.get_interpreter(archive)
Return the interpreter specified in the #! line at the start of the archive. If there is no #! line, return None. The archive argument can be a filename or a file-like object open for reading in bytes mode. It is assumed to be at the start of the archive.
Examples Pack up a directory into an archive, and run it. $ python -m zipapp myapp
$ python myapp.pyz
<output from myapp>
The same can be done using the create_archive() function: >>> import zipapp
>>> zipapp.create_archive('myapp', 'myapp.pyz')
To make the application directly executable on POSIX, specify an interpreter to use. $ python -m zipapp myapp -p "/usr/bin/env python"
$ ./myapp.pyz
<output from myapp>
To replace the shebang line on an existing archive, create a modified archive using the create_archive() function: >>> import zipapp
>>> zipapp.create_archive('old_archive.pyz', 'new_archive.pyz', '/usr/bin/python3')
To update the file in place, do the replacement in memory using a BytesIO object, and then overwrite the source afterwards. Note that there is a risk when overwriting a file in place that an error will result in the loss of the original file. This code does not protect against such errors, but production code should do so. Also, this method will only work if the archive fits in memory: >>> import zipapp
>>> import io
>>> temp = io.BytesIO()
>>> zipapp.create_archive('myapp.pyz', temp, '/usr/bin/python2')
>>> with open('myapp.pyz', 'wb') as f:
>>> f.write(temp.getvalue())
Specifying the Interpreter Note that if you specify an interpreter and then distribute your application archive, you need to ensure that the interpreter used is portable. The Python launcher for Windows supports most common forms of POSIX #! line, but there are other issues to consider: If you use “/usr/bin/env python” (or other forms of the “python” command, such as “/usr/bin/python”), you need to consider that your users may have either Python 2 or Python 3 as their default, and write your code to work under both versions. If you use an explicit version, for example “/usr/bin/env python3” your application will not work for users who do not have that version. (This may be what you want if you have not made your code Python 2 compatible). There is no way to say “python X.Y or later”, so be careful of using an exact version like “/usr/bin/env python3.4” as you will need to change your shebang line for users of Python 3.5, for example. Typically, you should use an “/usr/bin/env python2” or “/usr/bin/env python3”, depending on whether your code is written for Python 2 or 3. Creating Standalone Applications with zipapp Using the zipapp module, it is possible to create self-contained Python programs, which can be distributed to end users who only need to have a suitable version of Python installed on their system. The key to doing this is to bundle all of the application’s dependencies into the archive, along with the application code. The steps to create a standalone archive are as follows: Create your application in a directory as normal, so you have a myapp directory containing a __main__.py file, and any supporting application code.
Install all of your application’s dependencies into the myapp directory, using pip: $ python -m pip install -r requirements.txt --target myapp
(this assumes you have your project requirements in a requirements.txt file - if not, you can just list the dependencies manually on the pip command line). Optionally, delete the .dist-info directories created by pip in the myapp directory. These hold metadata for pip to manage the packages, and as you won’t be making any further use of pip they aren’t required - although it won’t do any harm if you leave them.
Package the application using: $ python -m zipapp -p "interpreter" myapp
This will produce a standalone executable, which can be run on any machine with the appropriate interpreter available. See Specifying the Interpreter for details. It can be shipped to users as a single file. On Unix, the myapp.pyz file is executable as it stands. You can rename the file to remove the .pyz extension if you prefer a “plain” command name. On Windows, the myapp.pyz[w] file is executable by virtue of the fact that the Python interpreter registers the .pyz and .pyzw file extensions when installed. Making a Windows executable On Windows, registration of the .pyz extension is optional, and furthermore, there are certain places that don’t recognise registered extensions “transparently” (the simplest example is that subprocess.run(['myapp']) won’t find your application - you need to explicitly specify the extension). On Windows, therefore, it is often preferable to create an executable from the zipapp. This is relatively easy, although it does require a C compiler. The basic approach relies on the fact that zipfiles can have arbitrary data prepended, and Windows exe files can have arbitrary data appended. So by creating a suitable launcher and tacking the .pyz file onto the end of it, you end up with a single-file executable that runs your application. A suitable launcher can be as simple as the following: #define Py_LIMITED_API 1
#include "Python.h"
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#ifdef WINDOWS
int WINAPI wWinMain(
HINSTANCE hInstance, /* handle to current instance */
HINSTANCE hPrevInstance, /* handle to previous instance */
LPWSTR lpCmdLine, /* pointer to command line */
int nCmdShow /* show state of window */
)
#else
int wmain()
#endif
{
wchar_t **myargv = _alloca((__argc + 1) * sizeof(wchar_t*));
myargv[0] = __wargv[0];
memcpy(myargv + 1, __wargv, __argc * sizeof(wchar_t *));
return Py_Main(__argc+1, myargv);
}
If you define the WINDOWS preprocessor symbol, this will generate a GUI executable, and without it, a console executable. To compile the executable, you can either just use the standard MSVC command line tools, or you can take advantage of the fact that distutils knows how to compile Python source: >>> from distutils.ccompiler import new_compiler
>>> import distutils.sysconfig
>>> import sys
>>> import os
>>> from pathlib import Path
>>> def compile(src):
>>> src = Path(src)
>>> cc = new_compiler()
>>> exe = src.stem
>>> cc.add_include_dir(distutils.sysconfig.get_python_inc())
>>> cc.add_library_dir(os.path.join(sys.base_exec_prefix, 'libs'))
>>> # First the CLI executable
>>> objs = cc.compile([str(src)])
>>> cc.link_executable(objs, exe)
>>> # Now the GUI executable
>>> cc.define_macro('WINDOWS')
>>> objs = cc.compile([str(src)])
>>> cc.link_executable(objs, exe + 'w')
>>> if __name__ == "__main__":
>>> compile("zastub.c")
The resulting launcher uses the “Limited ABI”, so it will run unchanged with any version of Python 3.x. All it needs is for Python (python3.dll) to be on the user’s PATH. For a fully standalone distribution, you can distribute the launcher with your application appended, bundled with the Python “embedded” distribution. This will run on any PC with the appropriate architecture (32 bit or 64 bit). Caveats There are some limitations to the process of bundling your application into a single file. In most, if not all, cases they can be addressed without needing major changes to your application. If your application depends on a package that includes a C extension, that package cannot be run from a zip file (this is an OS limitation, as executable code must be present in the filesystem for the OS loader to load it). In this case, you can exclude that dependency from the zipfile, and either require your users to have it installed, or ship it alongside your zipfile and add code to your __main__.py to include the directory containing the unzipped module in sys.path. In this case, you will need to make sure to ship appropriate binaries for your target architecture(s) (and potentially pick the correct version to add to sys.path at runtime, based on the user’s machine). If you are shipping a Windows executable as described above, you either need to ensure that your users have python3.dll on their PATH (which is not the default behaviour of the installer) or you should bundle your application with the embedded distribution. The suggested launcher above uses the Python embedding API. This means that in your application, sys.executable will be your application, and not a conventional Python interpreter. Your code and its dependencies need to be prepared for this possibility. For example, if your application uses the multiprocessing module, it will need to call multiprocessing.set_executable() to let the module know where to find the standard Python interpreter. The Python Zip Application Archive Format Python has been able to execute zip files which contain a __main__.py file since version 2.6. In order to be executed by Python, an application archive simply has to be a standard zip file containing a __main__.py file which will be run as the entry point for the application. As usual for any Python script, the parent of the script (in this case the zip file) will be placed on sys.path and thus further modules can be imported from the zip file. The zip file format allows arbitrary data to be prepended to a zip file. The zip application format uses this ability to prepend a standard POSIX “shebang” line to the file (#!/path/to/interpreter). Formally, the Python zip application format is therefore: An optional shebang line, containing the characters b'#!' followed by an interpreter name, and then a newline (b'\n') character. The interpreter name can be anything acceptable to the OS “shebang” processing, or the Python launcher on Windows. The interpreter should be encoded in UTF-8 on Windows, and in sys.getfilesystemencoding() on POSIX. Standard zipfile data, as generated by the zipfile module. The zipfile content must include a file called __main__.py (which must be in the “root” of the zipfile - i.e., it cannot be in a subdirectory). The zipfile data can be compressed or uncompressed. If an application archive has a shebang line, it may have the executable bit set on POSIX systems, to allow it to be executed directly. There is no requirement that the tools in this module are used to create application archives - the module is a convenience, but archives in the above format created by any means are acceptable to Python. | python.library.zipapp |
zipapp.create_archive(source, target=None, interpreter=None, main=None, filter=None, compressed=False)
Create an application archive from source. The source can be any of the following: The name of a directory, or a path-like object referring to a directory, in which case a new application archive will be created from the content of that directory. The name of an existing application archive file, or a path-like object referring to such a file, in which case the file is copied to the target (modifying it to reflect the value given for the interpreter argument). The file name should include the .pyz extension, if required. A file object open for reading in bytes mode. The content of the file should be an application archive, and the file object is assumed to be positioned at the start of the archive. The target argument determines where the resulting archive will be written: If it is the name of a file, or a path-like object, the archive will be written to that file. If it is an open file object, the archive will be written to that file object, which must be open for writing in bytes mode. If the target is omitted (or None), the source must be a directory and the target will be a file with the same name as the source, with a .pyz extension added. The interpreter argument specifies the name of the Python interpreter with which the archive will be executed. It is written as a “shebang” line at the start of the archive. On POSIX, this will be interpreted by the OS, and on Windows it will be handled by the Python launcher. Omitting the interpreter results in no shebang line being written. If an interpreter is specified, and the target is a filename, the executable bit of the target file will be set. The main argument specifies the name of a callable which will be used as the main program for the archive. It can only be specified if the source is a directory, and the source does not already contain a __main__.py file. The main argument should take the form “pkg.module:callable” and the archive will be run by importing “pkg.module” and executing the given callable with no arguments. It is an error to omit main if the source is a directory and does not contain a __main__.py file, as otherwise the resulting archive would not be executable. The optional filter argument specifies a callback function that is passed a Path object representing the path to the file being added (relative to the source directory). It should return True if the file is to be added. The optional compressed argument determines whether files are compressed. If set to True, files in the archive are compressed with the deflate method; otherwise, files are stored uncompressed. This argument has no effect when copying an existing archive. If a file object is specified for source or target, it is the caller’s responsibility to close it after calling create_archive. When copying an existing archive, file objects supplied only need read and readline, or write methods. When creating an archive from a directory, if the target is a file object it will be passed to the zipfile.ZipFile class, and must supply the methods needed by that class. New in version 3.7: Added the filter and compressed arguments. | python.library.zipapp#zipapp.create_archive |
zipapp.get_interpreter(archive)
Return the interpreter specified in the #! line at the start of the archive. If there is no #! line, return None. The archive argument can be a filename or a file-like object open for reading in bytes mode. It is assumed to be at the start of the archive. | python.library.zipapp#zipapp.get_interpreter |
zipfile — Work with ZIP archives Source code: Lib/zipfile.py The ZIP file format is a common archive and compression standard. This module provides tools to create, read, write, append, and list a ZIP file. Any advanced use of this module will require an understanding of the format, as defined in PKZIP Application Note. This module does not currently handle multi-disk ZIP files. It can handle ZIP files that use the ZIP64 extensions (that is ZIP files that are more than 4 GiB in size). It supports decryption of encrypted files in ZIP archives, but it currently cannot create an encrypted file. Decryption is extremely slow as it is implemented in native Python rather than C. The module defines the following items:
exception zipfile.BadZipFile
The error raised for bad ZIP files. New in version 3.2.
exception zipfile.BadZipfile
Alias of BadZipFile, for compatibility with older Python versions. Deprecated since version 3.2.
exception zipfile.LargeZipFile
The error raised when a ZIP file would require ZIP64 functionality but that has not been enabled.
class zipfile.ZipFile
The class for reading and writing ZIP files. See section ZipFile Objects for constructor details.
class zipfile.Path
A pathlib-compatible wrapper for zip files. See section Path Objects for details. New in version 3.8.
class zipfile.PyZipFile
Class for creating ZIP archives containing Python libraries.
class zipfile.ZipInfo(filename='NoName', date_time=(1980, 1, 1, 0, 0, 0))
Class used to represent information about a member of an archive. Instances of this class are returned by the getinfo() and infolist() methods of ZipFile objects. Most users of the zipfile module will not need to create these, but only use those created by this module. filename should be the full name of the archive member, and date_time should be a tuple containing six fields which describe the time of the last modification to the file; the fields are described in section ZipInfo Objects.
zipfile.is_zipfile(filename)
Returns True if filename is a valid ZIP file based on its magic number, otherwise returns False. filename may be a file or file-like object too. Changed in version 3.1: Support for file and file-like objects.
zipfile.ZIP_STORED
The numeric constant for an uncompressed archive member.
zipfile.ZIP_DEFLATED
The numeric constant for the usual ZIP compression method. This requires the zlib module.
zipfile.ZIP_BZIP2
The numeric constant for the BZIP2 compression method. This requires the bz2 module. New in version 3.3.
zipfile.ZIP_LZMA
The numeric constant for the LZMA compression method. This requires the lzma module. New in version 3.3. Note The ZIP file format specification has included support for bzip2 compression since 2001, and for LZMA compression since 2006. However, some tools (including older Python releases) do not support these compression methods, and may either refuse to process the ZIP file altogether, or fail to extract individual files.
See also PKZIP Application Note
Documentation on the ZIP file format by Phil Katz, the creator of the format and algorithms used. Info-ZIP Home Page
Information about the Info-ZIP project’s ZIP archive programs and development libraries. ZipFile Objects
class zipfile.ZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True, compresslevel=None, *, strict_timestamps=True)
Open a ZIP file, where file can be a path to a file (a string), a file-like object or a path-like object. The mode parameter should be 'r' to read an existing file, 'w' to truncate and write a new file, 'a' to append to an existing file, or 'x' to exclusively create and write a new file. If mode is 'x' and file refers to an existing file, a FileExistsError will be raised. If mode is 'a' and file refers to an existing ZIP file, then additional files are added to it. If file does not refer to a ZIP file, then a new ZIP archive is appended to the file. This is meant for adding a ZIP archive to another file (such as python.exe). If mode is 'a' and the file does not exist at all, it is created. If mode is 'r' or 'a', the file should be seekable. compression is the ZIP compression method to use when writing the archive, and should be ZIP_STORED, ZIP_DEFLATED, ZIP_BZIP2 or ZIP_LZMA; unrecognized values will cause NotImplementedError to be raised. If ZIP_DEFLATED, ZIP_BZIP2 or ZIP_LZMA is specified but the corresponding module (zlib, bz2 or lzma) is not available, RuntimeError is raised. The default is ZIP_STORED. If allowZip64 is True (the default) zipfile will create ZIP files that use the ZIP64 extensions when the zipfile is larger than 4 GiB. If it is false zipfile will raise an exception when the ZIP file would require ZIP64 extensions. The compresslevel parameter controls the compression level to use when writing files to the archive. When using ZIP_STORED or ZIP_LZMA it has no effect. When using ZIP_DEFLATED integers 0 through 9 are accepted (see zlib for more information). When using ZIP_BZIP2 integers 1 through 9 are accepted (see bz2 for more information). The strict_timestamps argument, when set to False, allows to zip files older than 1980-01-01 at the cost of setting the timestamp to 1980-01-01. Similar behavior occurs with files newer than 2107-12-31, the timestamp is also set to the limit. If the file is created with mode 'w', 'x' or 'a' and then closed without adding any files to the archive, the appropriate ZIP structures for an empty archive will be written to the file. ZipFile is also a context manager and therefore supports the with statement. In the example, myzip is closed after the with statement’s suite is finished—even if an exception occurs: with ZipFile('spam.zip', 'w') as myzip:
myzip.write('eggs.txt')
New in version 3.2: Added the ability to use ZipFile as a context manager. Changed in version 3.3: Added support for bzip2 and lzma compression. Changed in version 3.4: ZIP64 extensions are enabled by default. Changed in version 3.5: Added support for writing to unseekable streams. Added support for the 'x' mode. Changed in version 3.6: Previously, a plain RuntimeError was raised for unrecognized compression values. Changed in version 3.6.2: The file parameter accepts a path-like object. Changed in version 3.7: Add the compresslevel parameter. New in version 3.8: The strict_timestamps keyword-only argument
ZipFile.close()
Close the archive file. You must call close() before exiting your program or essential records will not be written.
ZipFile.getinfo(name)
Return a ZipInfo object with information about the archive member name. Calling getinfo() for a name not currently contained in the archive will raise a KeyError.
ZipFile.infolist()
Return a list containing a ZipInfo object for each member of the archive. The objects are in the same order as their entries in the actual ZIP file on disk if an existing archive was opened.
ZipFile.namelist()
Return a list of archive members by name.
ZipFile.open(name, mode='r', pwd=None, *, force_zip64=False)
Access a member of the archive as a binary file-like object. name can be either the name of a file within the archive or a ZipInfo object. The mode parameter, if included, must be 'r' (the default) or 'w'. pwd is the password used to decrypt encrypted ZIP files. open() is also a context manager and therefore supports the with statement: with ZipFile('spam.zip') as myzip:
with myzip.open('eggs.txt') as myfile:
print(myfile.read())
With mode 'r' the file-like object (ZipExtFile) is read-only and provides the following methods: read(), readline(), readlines(), seek(), tell(), __iter__(), __next__(). These objects can operate independently of the ZipFile. With mode='w', a writable file handle is returned, which supports the write() method. While a writable file handle is open, attempting to read or write other files in the ZIP file will raise a ValueError. When writing a file, if the file size is not known in advance but may exceed 2 GiB, pass force_zip64=True to ensure that the header format is capable of supporting large files. If the file size is known in advance, construct a ZipInfo object with file_size set, and use that as the name parameter. Note The open(), read() and extract() methods can take a filename or a ZipInfo object. You will appreciate this when trying to read a ZIP file that contains members with duplicate names. Changed in version 3.6: Removed support of mode='U'. Use io.TextIOWrapper for reading compressed text files in universal newlines mode. Changed in version 3.6: open() can now be used to write files into the archive with the mode='w' option. Changed in version 3.6: Calling open() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.
ZipFile.extract(member, path=None, pwd=None)
Extract a member from the archive to the current working directory; member must be its full name or a ZipInfo object. Its file information is extracted as accurately as possible. path specifies a different directory to extract to. member can be a filename or a ZipInfo object. pwd is the password used for encrypted files. Returns the normalized path created (a directory or new file). Note If a member filename is an absolute path, a drive/UNC sharepoint and leading (back)slashes will be stripped, e.g.: ///foo/bar becomes foo/bar on Unix, and C:\foo\bar becomes foo\bar on Windows. And all ".." components in a member filename will be removed, e.g.: ../../foo../../ba..r becomes foo../ba..r. On Windows illegal characters (:, <, >, |, ", ?, and *) replaced by underscore (_). Changed in version 3.6: Calling extract() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised. Changed in version 3.6.2: The path parameter accepts a path-like object.
ZipFile.extractall(path=None, members=None, pwd=None)
Extract all members from the archive to the current working directory. path specifies a different directory to extract to. members is optional and must be a subset of the list returned by namelist(). pwd is the password used for encrypted files. Warning Never extract archives from untrusted sources without prior inspection. It is possible that files are created outside of path, e.g. members that have absolute filenames starting with "/" or filenames with two dots "..". This module attempts to prevent that. See extract() note. Changed in version 3.6: Calling extractall() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised. Changed in version 3.6.2: The path parameter accepts a path-like object.
ZipFile.printdir()
Print a table of contents for the archive to sys.stdout.
ZipFile.setpassword(pwd)
Set pwd as default password to extract encrypted files.
ZipFile.read(name, pwd=None)
Return the bytes of the file name in the archive. name is the name of the file in the archive, or a ZipInfo object. The archive must be open for read or append. pwd is the password used for encrypted files and, if specified, it will override the default password set with setpassword(). Calling read() on a ZipFile that uses a compression method other than ZIP_STORED, ZIP_DEFLATED, ZIP_BZIP2 or ZIP_LZMA will raise a NotImplementedError. An error will also be raised if the corresponding compression module is not available. Changed in version 3.6: Calling read() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.
ZipFile.testzip()
Read all the files in the archive and check their CRC’s and file headers. Return the name of the first bad file, or else return None. Changed in version 3.6: Calling testzip() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.
ZipFile.write(filename, arcname=None, compress_type=None, compresslevel=None)
Write the file named filename to the archive, giving it the archive name arcname (by default, this will be the same as filename, but without a drive letter and with leading path separators removed). If given, compress_type overrides the value given for the compression parameter to the constructor for the new entry. Similarly, compresslevel will override the constructor if given. The archive must be open with mode 'w', 'x' or 'a'. Note Archive names should be relative to the archive root, that is, they should not start with a path separator. Note If arcname (or filename, if arcname is not given) contains a null byte, the name of the file in the archive will be truncated at the null byte. Changed in version 3.6: Calling write() on a ZipFile created with mode 'r' or a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.
ZipFile.writestr(zinfo_or_arcname, data, compress_type=None, compresslevel=None)
Write a file into the archive. The contents is data, which may be either a str or a bytes instance; if it is a str, it is encoded as UTF-8 first. zinfo_or_arcname is either the file name it will be given in the archive, or a ZipInfo instance. If it’s an instance, at least the filename, date, and time must be given. If it’s a name, the date and time is set to the current date and time. The archive must be opened with mode 'w', 'x' or 'a'. If given, compress_type overrides the value given for the compression parameter to the constructor for the new entry, or in the zinfo_or_arcname (if that is a ZipInfo instance). Similarly, compresslevel will override the constructor if given. Note When passing a ZipInfo instance as the zinfo_or_arcname parameter, the compression method used will be that specified in the compress_type member of the given ZipInfo instance. By default, the ZipInfo constructor sets this member to ZIP_STORED. Changed in version 3.2: The compress_type argument. Changed in version 3.6: Calling writestr() on a ZipFile created with mode 'r' or a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised.
The following data attributes are also available:
ZipFile.filename
Name of the ZIP file.
ZipFile.debug
The level of debug output to use. This may be set from 0 (the default, no output) to 3 (the most output). Debugging information is written to sys.stdout.
ZipFile.comment
The comment associated with the ZIP file as a bytes object. If assigning a comment to a ZipFile instance created with mode 'w', 'x' or 'a', it should be no longer than 65535 bytes. Comments longer than this will be truncated.
Path Objects
class zipfile.Path(root, at='')
Construct a Path object from a root zipfile (which may be a ZipFile instance or file suitable for passing to the ZipFile constructor). at specifies the location of this Path within the zipfile, e.g. ‘dir/file.txt’, ‘dir/’, or ‘’. Defaults to the empty string, indicating the root.
Path objects expose the following features of pathlib.Path objects: Path objects are traversable using the / operator.
Path.name
The final path component.
Path.open(mode='r', *, pwd, **)
Invoke ZipFile.open() on the current path. Allows opening for read or write, text or binary through supported modes: ‘r’, ‘w’, ‘rb’, ‘wb’. Positional and keyword arguments are passed through to io.TextIOWrapper when opened as text and ignored otherwise. pwd is the pwd parameter to ZipFile.open(). Changed in version 3.9: Added support for text and binary modes for open. Default mode is now text.
Path.iterdir()
Enumerate the children of the current directory.
Path.is_dir()
Return True if the current context references a directory.
Path.is_file()
Return True if the current context references a file.
Path.exists()
Return True if the current context references a file or directory in the zip file.
Path.read_text(*, **)
Read the current file as unicode text. Positional and keyword arguments are passed through to io.TextIOWrapper (except buffer, which is implied by the context).
Path.read_bytes()
Read the current file as bytes.
PyZipFile Objects The PyZipFile constructor takes the same parameters as the ZipFile constructor, and one additional parameter, optimize.
class zipfile.PyZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True, optimize=-1)
New in version 3.2: The optimize parameter. Changed in version 3.4: ZIP64 extensions are enabled by default. Instances have one method in addition to those of ZipFile objects:
writepy(pathname, basename='', filterfunc=None)
Search for files *.py and add the corresponding file to the archive. If the optimize parameter to PyZipFile was not given or -1, the corresponding file is a *.pyc file, compiling if necessary. If the optimize parameter to PyZipFile was 0, 1 or 2, only files with that optimization level (see compile()) are added to the archive, compiling if necessary. If pathname is a file, the filename must end with .py, and just the (corresponding *.pyc) file is added at the top level (no path information). If pathname is a file that does not end with .py, a RuntimeError will be raised. If it is a directory, and the directory is not a package directory, then all the files *.pyc are added at the top level. If the directory is a package directory, then all *.pyc are added under the package name as a file path, and if any subdirectories are package directories, all of these are added recursively in sorted order. basename is intended for internal use only. filterfunc, if given, must be a function taking a single string argument. It will be passed each path (including each individual full file path) before it is added to the archive. If filterfunc returns a false value, the path will not be added, and if it is a directory its contents will be ignored. For example, if our test files are all either in test directories or start with the string test_, we can use a filterfunc to exclude them: >>> zf = PyZipFile('myprog.zip')
>>> def notests(s):
... fn = os.path.basename(s)
... return (not (fn == 'test' or fn.startswith('test_')))
>>> zf.writepy('myprog', filterfunc=notests)
The writepy() method makes archives with file names like this: string.pyc # Top level name
test/__init__.pyc # Package directory
test/testall.pyc # Module test.testall
test/bogus/__init__.pyc # Subpackage directory
test/bogus/myfile.pyc # Submodule test.bogus.myfile
New in version 3.4: The filterfunc parameter. Changed in version 3.6.2: The pathname parameter accepts a path-like object. Changed in version 3.7: Recursion sorts directory entries.
ZipInfo Objects Instances of the ZipInfo class are returned by the getinfo() and infolist() methods of ZipFile objects. Each object stores information about a single member of the ZIP archive. There is one classmethod to make a ZipInfo instance for a filesystem file:
classmethod ZipInfo.from_file(filename, arcname=None, *, strict_timestamps=True)
Construct a ZipInfo instance for a file on the filesystem, in preparation for adding it to a zip file. filename should be the path to a file or directory on the filesystem. If arcname is specified, it is used as the name within the archive. If arcname is not specified, the name will be the same as filename, but with any drive letter and leading path separators removed. The strict_timestamps argument, when set to False, allows to zip files older than 1980-01-01 at the cost of setting the timestamp to 1980-01-01. Similar behavior occurs with files newer than 2107-12-31, the timestamp is also set to the limit. New in version 3.6. Changed in version 3.6.2: The filename parameter accepts a path-like object. New in version 3.8: The strict_timestamps keyword-only argument
Instances have the following methods and attributes:
ZipInfo.is_dir()
Return True if this archive member is a directory. This uses the entry’s name: directories should always end with /. New in version 3.6.
ZipInfo.filename
Name of the file in the archive.
ZipInfo.date_time
The time and date of the last modification to the archive member. This is a tuple of six values:
Index Value
0 Year (>= 1980)
1 Month (one-based)
2 Day of month (one-based)
3 Hours (zero-based)
4 Minutes (zero-based)
5 Seconds (zero-based) Note The ZIP file format does not support timestamps before 1980.
ZipInfo.compress_type
Type of compression for the archive member.
ZipInfo.comment
Comment for the individual archive member as a bytes object.
ZipInfo.extra
Expansion field data. The PKZIP Application Note contains some comments on the internal structure of the data contained in this bytes object.
ZipInfo.create_system
System which created ZIP archive.
ZipInfo.create_version
PKZIP version which created ZIP archive.
ZipInfo.extract_version
PKZIP version needed to extract archive.
ZipInfo.reserved
Must be zero.
ZipInfo.flag_bits
ZIP flag bits.
ZipInfo.volume
Volume number of file header.
ZipInfo.internal_attr
Internal attributes.
ZipInfo.external_attr
External file attributes.
ZipInfo.header_offset
Byte offset to the file header.
ZipInfo.CRC
CRC-32 of the uncompressed file.
ZipInfo.compress_size
Size of the compressed data.
ZipInfo.file_size
Size of the uncompressed file.
Command-Line Interface The zipfile module provides a simple command-line interface to interact with ZIP archives. If you want to create a new ZIP archive, specify its name after the -c option and then list the filename(s) that should be included: $ python -m zipfile -c monty.zip spam.txt eggs.txt
Passing a directory is also acceptable: $ python -m zipfile -c monty.zip life-of-brian_1979/
If you want to extract a ZIP archive into the specified directory, use the -e option: $ python -m zipfile -e monty.zip target-dir/
For a list of the files in a ZIP archive, use the -l option: $ python -m zipfile -l monty.zip
Command-line options
-l <zipfile>
--list <zipfile>
List files in a zipfile.
-c <zipfile> <source1> ... <sourceN>
--create <zipfile> <source1> ... <sourceN>
Create zipfile from source files.
-e <zipfile> <output_dir>
--extract <zipfile> <output_dir>
Extract zipfile into target directory.
-t <zipfile>
--test <zipfile>
Test whether the zipfile is valid or not.
Decompression pitfalls The extraction in zipfile module might fail due to some pitfalls listed below. From file itself Decompression may fail due to incorrect password / CRC checksum / ZIP format or unsupported compression method / decryption. File System limitations Exceeding limitations on different file systems can cause decompression failed. Such as allowable characters in the directory entries, length of the file name, length of the pathname, size of a single file, and number of files, etc. Resources limitations The lack of memory or disk volume would lead to decompression failed. For example, decompression bombs (aka ZIP bomb) apply to zipfile library that can cause disk volume exhaustion. Interruption Interruption during the decompression, such as pressing control-C or killing the decompression process may result in incomplete decompression of the archive. Default behaviors of extraction Not knowing the default extraction behaviors can cause unexpected decompression results. For example, when extracting the same archive twice, it overwrites files without asking. | python.library.zipfile |
exception zipfile.BadZipfile
Alias of BadZipFile, for compatibility with older Python versions. Deprecated since version 3.2. | python.library.zipfile#zipfile.BadZipfile |
exception zipfile.BadZipFile
The error raised for bad ZIP files. New in version 3.2. | python.library.zipfile#zipfile.BadZipFile |
zipfile.is_zipfile(filename)
Returns True if filename is a valid ZIP file based on its magic number, otherwise returns False. filename may be a file or file-like object too. Changed in version 3.1: Support for file and file-like objects. | python.library.zipfile#zipfile.is_zipfile |
exception zipfile.LargeZipFile
The error raised when a ZIP file would require ZIP64 functionality but that has not been enabled. | python.library.zipfile#zipfile.LargeZipFile |
class zipfile.Path(root, at='')
Construct a Path object from a root zipfile (which may be a ZipFile instance or file suitable for passing to the ZipFile constructor). at specifies the location of this Path within the zipfile, e.g. ‘dir/file.txt’, ‘dir/’, or ‘’. Defaults to the empty string, indicating the root. | python.library.zipfile#zipfile.Path |
Path.exists()
Return True if the current context references a file or directory in the zip file. | python.library.zipfile#zipfile.Path.exists |
Path.is_dir()
Return True if the current context references a directory. | python.library.zipfile#zipfile.Path.is_dir |
Path.is_file()
Return True if the current context references a file. | python.library.zipfile#zipfile.Path.is_file |
Path.iterdir()
Enumerate the children of the current directory. | python.library.zipfile#zipfile.Path.iterdir |
Path.name
The final path component. | python.library.zipfile#zipfile.Path.name |
Path.open(mode='r', *, pwd, **)
Invoke ZipFile.open() on the current path. Allows opening for read or write, text or binary through supported modes: ‘r’, ‘w’, ‘rb’, ‘wb’. Positional and keyword arguments are passed through to io.TextIOWrapper when opened as text and ignored otherwise. pwd is the pwd parameter to ZipFile.open(). Changed in version 3.9: Added support for text and binary modes for open. Default mode is now text. | python.library.zipfile#zipfile.Path.open |
Path.read_bytes()
Read the current file as bytes. | python.library.zipfile#zipfile.Path.read_bytes |
Path.read_text(*, **)
Read the current file as unicode text. Positional and keyword arguments are passed through to io.TextIOWrapper (except buffer, which is implied by the context). | python.library.zipfile#zipfile.Path.read_text |
class zipfile.PyZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True, optimize=-1)
New in version 3.2: The optimize parameter. Changed in version 3.4: ZIP64 extensions are enabled by default. Instances have one method in addition to those of ZipFile objects:
writepy(pathname, basename='', filterfunc=None)
Search for files *.py and add the corresponding file to the archive. If the optimize parameter to PyZipFile was not given or -1, the corresponding file is a *.pyc file, compiling if necessary. If the optimize parameter to PyZipFile was 0, 1 or 2, only files with that optimization level (see compile()) are added to the archive, compiling if necessary. If pathname is a file, the filename must end with .py, and just the (corresponding *.pyc) file is added at the top level (no path information). If pathname is a file that does not end with .py, a RuntimeError will be raised. If it is a directory, and the directory is not a package directory, then all the files *.pyc are added at the top level. If the directory is a package directory, then all *.pyc are added under the package name as a file path, and if any subdirectories are package directories, all of these are added recursively in sorted order. basename is intended for internal use only. filterfunc, if given, must be a function taking a single string argument. It will be passed each path (including each individual full file path) before it is added to the archive. If filterfunc returns a false value, the path will not be added, and if it is a directory its contents will be ignored. For example, if our test files are all either in test directories or start with the string test_, we can use a filterfunc to exclude them: >>> zf = PyZipFile('myprog.zip')
>>> def notests(s):
... fn = os.path.basename(s)
... return (not (fn == 'test' or fn.startswith('test_')))
>>> zf.writepy('myprog', filterfunc=notests)
The writepy() method makes archives with file names like this: string.pyc # Top level name
test/__init__.pyc # Package directory
test/testall.pyc # Module test.testall
test/bogus/__init__.pyc # Subpackage directory
test/bogus/myfile.pyc # Submodule test.bogus.myfile
New in version 3.4: The filterfunc parameter. Changed in version 3.6.2: The pathname parameter accepts a path-like object. Changed in version 3.7: Recursion sorts directory entries. | python.library.zipfile#zipfile.PyZipFile |
writepy(pathname, basename='', filterfunc=None)
Search for files *.py and add the corresponding file to the archive. If the optimize parameter to PyZipFile was not given or -1, the corresponding file is a *.pyc file, compiling if necessary. If the optimize parameter to PyZipFile was 0, 1 or 2, only files with that optimization level (see compile()) are added to the archive, compiling if necessary. If pathname is a file, the filename must end with .py, and just the (corresponding *.pyc) file is added at the top level (no path information). If pathname is a file that does not end with .py, a RuntimeError will be raised. If it is a directory, and the directory is not a package directory, then all the files *.pyc are added at the top level. If the directory is a package directory, then all *.pyc are added under the package name as a file path, and if any subdirectories are package directories, all of these are added recursively in sorted order. basename is intended for internal use only. filterfunc, if given, must be a function taking a single string argument. It will be passed each path (including each individual full file path) before it is added to the archive. If filterfunc returns a false value, the path will not be added, and if it is a directory its contents will be ignored. For example, if our test files are all either in test directories or start with the string test_, we can use a filterfunc to exclude them: >>> zf = PyZipFile('myprog.zip')
>>> def notests(s):
... fn = os.path.basename(s)
... return (not (fn == 'test' or fn.startswith('test_')))
>>> zf.writepy('myprog', filterfunc=notests)
The writepy() method makes archives with file names like this: string.pyc # Top level name
test/__init__.pyc # Package directory
test/testall.pyc # Module test.testall
test/bogus/__init__.pyc # Subpackage directory
test/bogus/myfile.pyc # Submodule test.bogus.myfile
New in version 3.4: The filterfunc parameter. Changed in version 3.6.2: The pathname parameter accepts a path-like object. Changed in version 3.7: Recursion sorts directory entries. | python.library.zipfile#zipfile.PyZipFile.writepy |
class zipfile.ZipFile(file, mode='r', compression=ZIP_STORED, allowZip64=True, compresslevel=None, *, strict_timestamps=True)
Open a ZIP file, where file can be a path to a file (a string), a file-like object or a path-like object. The mode parameter should be 'r' to read an existing file, 'w' to truncate and write a new file, 'a' to append to an existing file, or 'x' to exclusively create and write a new file. If mode is 'x' and file refers to an existing file, a FileExistsError will be raised. If mode is 'a' and file refers to an existing ZIP file, then additional files are added to it. If file does not refer to a ZIP file, then a new ZIP archive is appended to the file. This is meant for adding a ZIP archive to another file (such as python.exe). If mode is 'a' and the file does not exist at all, it is created. If mode is 'r' or 'a', the file should be seekable. compression is the ZIP compression method to use when writing the archive, and should be ZIP_STORED, ZIP_DEFLATED, ZIP_BZIP2 or ZIP_LZMA; unrecognized values will cause NotImplementedError to be raised. If ZIP_DEFLATED, ZIP_BZIP2 or ZIP_LZMA is specified but the corresponding module (zlib, bz2 or lzma) is not available, RuntimeError is raised. The default is ZIP_STORED. If allowZip64 is True (the default) zipfile will create ZIP files that use the ZIP64 extensions when the zipfile is larger than 4 GiB. If it is false zipfile will raise an exception when the ZIP file would require ZIP64 extensions. The compresslevel parameter controls the compression level to use when writing files to the archive. When using ZIP_STORED or ZIP_LZMA it has no effect. When using ZIP_DEFLATED integers 0 through 9 are accepted (see zlib for more information). When using ZIP_BZIP2 integers 1 through 9 are accepted (see bz2 for more information). The strict_timestamps argument, when set to False, allows to zip files older than 1980-01-01 at the cost of setting the timestamp to 1980-01-01. Similar behavior occurs with files newer than 2107-12-31, the timestamp is also set to the limit. If the file is created with mode 'w', 'x' or 'a' and then closed without adding any files to the archive, the appropriate ZIP structures for an empty archive will be written to the file. ZipFile is also a context manager and therefore supports the with statement. In the example, myzip is closed after the with statement’s suite is finished—even if an exception occurs: with ZipFile('spam.zip', 'w') as myzip:
myzip.write('eggs.txt')
New in version 3.2: Added the ability to use ZipFile as a context manager. Changed in version 3.3: Added support for bzip2 and lzma compression. Changed in version 3.4: ZIP64 extensions are enabled by default. Changed in version 3.5: Added support for writing to unseekable streams. Added support for the 'x' mode. Changed in version 3.6: Previously, a plain RuntimeError was raised for unrecognized compression values. Changed in version 3.6.2: The file parameter accepts a path-like object. Changed in version 3.7: Add the compresslevel parameter. New in version 3.8: The strict_timestamps keyword-only argument | python.library.zipfile#zipfile.ZipFile |
ZipFile.close()
Close the archive file. You must call close() before exiting your program or essential records will not be written. | python.library.zipfile#zipfile.ZipFile.close |
ZipFile.comment
The comment associated with the ZIP file as a bytes object. If assigning a comment to a ZipFile instance created with mode 'w', 'x' or 'a', it should be no longer than 65535 bytes. Comments longer than this will be truncated. | python.library.zipfile#zipfile.ZipFile.comment |
ZipFile.debug
The level of debug output to use. This may be set from 0 (the default, no output) to 3 (the most output). Debugging information is written to sys.stdout. | python.library.zipfile#zipfile.ZipFile.debug |
ZipFile.extract(member, path=None, pwd=None)
Extract a member from the archive to the current working directory; member must be its full name or a ZipInfo object. Its file information is extracted as accurately as possible. path specifies a different directory to extract to. member can be a filename or a ZipInfo object. pwd is the password used for encrypted files. Returns the normalized path created (a directory or new file). Note If a member filename is an absolute path, a drive/UNC sharepoint and leading (back)slashes will be stripped, e.g.: ///foo/bar becomes foo/bar on Unix, and C:\foo\bar becomes foo\bar on Windows. And all ".." components in a member filename will be removed, e.g.: ../../foo../../ba..r becomes foo../ba..r. On Windows illegal characters (:, <, >, |, ", ?, and *) replaced by underscore (_). Changed in version 3.6: Calling extract() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised. Changed in version 3.6.2: The path parameter accepts a path-like object. | python.library.zipfile#zipfile.ZipFile.extract |
ZipFile.extractall(path=None, members=None, pwd=None)
Extract all members from the archive to the current working directory. path specifies a different directory to extract to. members is optional and must be a subset of the list returned by namelist(). pwd is the password used for encrypted files. Warning Never extract archives from untrusted sources without prior inspection. It is possible that files are created outside of path, e.g. members that have absolute filenames starting with "/" or filenames with two dots "..". This module attempts to prevent that. See extract() note. Changed in version 3.6: Calling extractall() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised. Changed in version 3.6.2: The path parameter accepts a path-like object. | python.library.zipfile#zipfile.ZipFile.extractall |
ZipFile.filename
Name of the ZIP file. | python.library.zipfile#zipfile.ZipFile.filename |
ZipFile.getinfo(name)
Return a ZipInfo object with information about the archive member name. Calling getinfo() for a name not currently contained in the archive will raise a KeyError. | python.library.zipfile#zipfile.ZipFile.getinfo |
ZipFile.infolist()
Return a list containing a ZipInfo object for each member of the archive. The objects are in the same order as their entries in the actual ZIP file on disk if an existing archive was opened. | python.library.zipfile#zipfile.ZipFile.infolist |
ZipFile.namelist()
Return a list of archive members by name. | python.library.zipfile#zipfile.ZipFile.namelist |
ZipFile.open(name, mode='r', pwd=None, *, force_zip64=False)
Access a member of the archive as a binary file-like object. name can be either the name of a file within the archive or a ZipInfo object. The mode parameter, if included, must be 'r' (the default) or 'w'. pwd is the password used to decrypt encrypted ZIP files. open() is also a context manager and therefore supports the with statement: with ZipFile('spam.zip') as myzip:
with myzip.open('eggs.txt') as myfile:
print(myfile.read())
With mode 'r' the file-like object (ZipExtFile) is read-only and provides the following methods: read(), readline(), readlines(), seek(), tell(), __iter__(), __next__(). These objects can operate independently of the ZipFile. With mode='w', a writable file handle is returned, which supports the write() method. While a writable file handle is open, attempting to read or write other files in the ZIP file will raise a ValueError. When writing a file, if the file size is not known in advance but may exceed 2 GiB, pass force_zip64=True to ensure that the header format is capable of supporting large files. If the file size is known in advance, construct a ZipInfo object with file_size set, and use that as the name parameter. Note The open(), read() and extract() methods can take a filename or a ZipInfo object. You will appreciate this when trying to read a ZIP file that contains members with duplicate names. Changed in version 3.6: Removed support of mode='U'. Use io.TextIOWrapper for reading compressed text files in universal newlines mode. Changed in version 3.6: open() can now be used to write files into the archive with the mode='w' option. Changed in version 3.6: Calling open() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised. | python.library.zipfile#zipfile.ZipFile.open |
ZipFile.printdir()
Print a table of contents for the archive to sys.stdout. | python.library.zipfile#zipfile.ZipFile.printdir |
ZipFile.read(name, pwd=None)
Return the bytes of the file name in the archive. name is the name of the file in the archive, or a ZipInfo object. The archive must be open for read or append. pwd is the password used for encrypted files and, if specified, it will override the default password set with setpassword(). Calling read() on a ZipFile that uses a compression method other than ZIP_STORED, ZIP_DEFLATED, ZIP_BZIP2 or ZIP_LZMA will raise a NotImplementedError. An error will also be raised if the corresponding compression module is not available. Changed in version 3.6: Calling read() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised. | python.library.zipfile#zipfile.ZipFile.read |
ZipFile.setpassword(pwd)
Set pwd as default password to extract encrypted files. | python.library.zipfile#zipfile.ZipFile.setpassword |
ZipFile.testzip()
Read all the files in the archive and check their CRC’s and file headers. Return the name of the first bad file, or else return None. Changed in version 3.6: Calling testzip() on a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised. | python.library.zipfile#zipfile.ZipFile.testzip |
ZipFile.write(filename, arcname=None, compress_type=None, compresslevel=None)
Write the file named filename to the archive, giving it the archive name arcname (by default, this will be the same as filename, but without a drive letter and with leading path separators removed). If given, compress_type overrides the value given for the compression parameter to the constructor for the new entry. Similarly, compresslevel will override the constructor if given. The archive must be open with mode 'w', 'x' or 'a'. Note Archive names should be relative to the archive root, that is, they should not start with a path separator. Note If arcname (or filename, if arcname is not given) contains a null byte, the name of the file in the archive will be truncated at the null byte. Changed in version 3.6: Calling write() on a ZipFile created with mode 'r' or a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised. | python.library.zipfile#zipfile.ZipFile.write |
ZipFile.writestr(zinfo_or_arcname, data, compress_type=None, compresslevel=None)
Write a file into the archive. The contents is data, which may be either a str or a bytes instance; if it is a str, it is encoded as UTF-8 first. zinfo_or_arcname is either the file name it will be given in the archive, or a ZipInfo instance. If it’s an instance, at least the filename, date, and time must be given. If it’s a name, the date and time is set to the current date and time. The archive must be opened with mode 'w', 'x' or 'a'. If given, compress_type overrides the value given for the compression parameter to the constructor for the new entry, or in the zinfo_or_arcname (if that is a ZipInfo instance). Similarly, compresslevel will override the constructor if given. Note When passing a ZipInfo instance as the zinfo_or_arcname parameter, the compression method used will be that specified in the compress_type member of the given ZipInfo instance. By default, the ZipInfo constructor sets this member to ZIP_STORED. Changed in version 3.2: The compress_type argument. Changed in version 3.6: Calling writestr() on a ZipFile created with mode 'r' or a closed ZipFile will raise a ValueError. Previously, a RuntimeError was raised. | python.library.zipfile#zipfile.ZipFile.writestr |
class zipfile.ZipInfo(filename='NoName', date_time=(1980, 1, 1, 0, 0, 0))
Class used to represent information about a member of an archive. Instances of this class are returned by the getinfo() and infolist() methods of ZipFile objects. Most users of the zipfile module will not need to create these, but only use those created by this module. filename should be the full name of the archive member, and date_time should be a tuple containing six fields which describe the time of the last modification to the file; the fields are described in section ZipInfo Objects. | python.library.zipfile#zipfile.ZipInfo |
ZipInfo.comment
Comment for the individual archive member as a bytes object. | python.library.zipfile#zipfile.ZipInfo.comment |
ZipInfo.compress_size
Size of the compressed data. | python.library.zipfile#zipfile.ZipInfo.compress_size |
ZipInfo.compress_type
Type of compression for the archive member. | python.library.zipfile#zipfile.ZipInfo.compress_type |
ZipInfo.CRC
CRC-32 of the uncompressed file. | python.library.zipfile#zipfile.ZipInfo.CRC |
ZipInfo.create_system
System which created ZIP archive. | python.library.zipfile#zipfile.ZipInfo.create_system |
ZipInfo.create_version
PKZIP version which created ZIP archive. | python.library.zipfile#zipfile.ZipInfo.create_version |
ZipInfo.date_time
The time and date of the last modification to the archive member. This is a tuple of six values:
Index Value
0 Year (>= 1980)
1 Month (one-based)
2 Day of month (one-based)
3 Hours (zero-based)
4 Minutes (zero-based)
5 Seconds (zero-based) Note The ZIP file format does not support timestamps before 1980. | python.library.zipfile#zipfile.ZipInfo.date_time |
ZipInfo.external_attr
External file attributes. | python.library.zipfile#zipfile.ZipInfo.external_attr |
ZipInfo.extra
Expansion field data. The PKZIP Application Note contains some comments on the internal structure of the data contained in this bytes object. | python.library.zipfile#zipfile.ZipInfo.extra |
ZipInfo.extract_version
PKZIP version needed to extract archive. | python.library.zipfile#zipfile.ZipInfo.extract_version |
ZipInfo.filename
Name of the file in the archive. | python.library.zipfile#zipfile.ZipInfo.filename |
ZipInfo.file_size
Size of the uncompressed file. | python.library.zipfile#zipfile.ZipInfo.file_size |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.