code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def makefile(self, mode='r', bufsize=-1): """Make and return a file-like object that works with the SSL connection. Just use the code from the socket module.""" self._makefile_refs += 1 # close=True so as to decrement the reference count when done with # the file-like object. return _fileobject(self, mode, bufsize, close=True)
Make and return a file-like object that works with the SSL connection. Just use the code from the socket module.
makefile
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ssl.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ssl.py
MIT
def get_channel_binding(self, cb_type="tls-unique"): """Get channel binding data for current connection. Raise ValueError if the requested `cb_type` is not supported. Return bytes of the data or None if the data is not available (e.g. before the handshake). """ if cb_type not in CHANNEL_BINDING_TYPES: raise ValueError("Unsupported channel binding type") if cb_type != "tls-unique": raise NotImplementedError( "{0} channel binding type not implemented" .format(cb_type)) if self._sslobj is None: return None return self._sslobj.tls_unique_cb()
Get channel binding data for current connection. Raise ValueError if the requested `cb_type` is not supported. Return bytes of the data or None if the data is not available (e.g. before the handshake).
get_channel_binding
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ssl.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ssl.py
MIT
def version(self): """ Return a string identifying the protocol version used by the current SSL channel, or None if there is no established channel. """ if self._sslobj is None: return None return self._sslobj.version()
Return a string identifying the protocol version used by the current SSL channel, or None if there is no established channel.
version
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ssl.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ssl.py
MIT
def cert_time_to_seconds(cert_time): """Return the time in seconds since the Epoch, given the timestring representing the "notBefore" or "notAfter" date from a certificate in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale). "notBefore" or "notAfter" dates must use UTC (RFC 5280). Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec UTC should be specified as GMT (see ASN1_TIME_print()) """ from time import strptime from calendar import timegm months = ( "Jan","Feb","Mar","Apr","May","Jun", "Jul","Aug","Sep","Oct","Nov","Dec" ) time_format = ' %d %H:%M:%S %Y GMT' # NOTE: no month, fixed GMT try: month_number = months.index(cert_time[:3].title()) + 1 except ValueError: raise ValueError('time data %r does not match ' 'format "%%b%s"' % (cert_time, time_format)) else: # found valid month tt = strptime(cert_time[3:], time_format) # return an integer, the previous mktime()-based implementation # returned a float (fractional seconds are always zero here). return timegm((tt[0], month_number) + tt[2:6])
Return the time in seconds since the Epoch, given the timestring representing the "notBefore" or "notAfter" date from a certificate in ``"%b %d %H:%M:%S %Y %Z"`` strptime format (C locale). "notBefore" or "notAfter" dates must use UTC (RFC 5280). Month is one of: Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec UTC should be specified as GMT (see ASN1_TIME_print())
cert_time_to_seconds
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ssl.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ssl.py
MIT
def DER_cert_to_PEM_cert(der_cert_bytes): """Takes a certificate in binary DER format and returns the PEM version of it as a string.""" f = base64.standard_b64encode(der_cert_bytes).decode('ascii') return (PEM_HEADER + '\n' + textwrap.fill(f, 64) + '\n' + PEM_FOOTER + '\n')
Takes a certificate in binary DER format and returns the PEM version of it as a string.
DER_cert_to_PEM_cert
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ssl.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ssl.py
MIT
def PEM_cert_to_DER_cert(pem_cert_string): """Takes a certificate in ASCII PEM format and returns the DER-encoded version of it as a byte sequence""" if not pem_cert_string.startswith(PEM_HEADER): raise ValueError("Invalid PEM encoding; must start with %s" % PEM_HEADER) if not pem_cert_string.strip().endswith(PEM_FOOTER): raise ValueError("Invalid PEM encoding; must end with %s" % PEM_FOOTER) d = pem_cert_string.strip()[len(PEM_HEADER):-len(PEM_FOOTER)] return base64.decodestring(d.encode('ASCII', 'strict'))
Takes a certificate in ASCII PEM format and returns the DER-encoded version of it as a byte sequence
PEM_cert_to_DER_cert
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ssl.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ssl.py
MIT
def get_server_certificate(addr, ssl_version=PROTOCOL_SSLv23, ca_certs=None): """Retrieve the certificate from the server at the specified address, and return it as a PEM-encoded string. If 'ca_certs' is specified, validate the server cert against it. If 'ssl_version' is specified, use it in the connection attempt.""" host, port = addr if ca_certs is not None: cert_reqs = CERT_REQUIRED else: cert_reqs = CERT_NONE context = _create_stdlib_context(ssl_version, cert_reqs=cert_reqs, cafile=ca_certs) with closing(create_connection(addr)) as sock: with closing(context.wrap_socket(sock)) as sslsock: dercert = sslsock.getpeercert(True) return DER_cert_to_PEM_cert(dercert)
Retrieve the certificate from the server at the specified address, and return it as a PEM-encoded string. If 'ca_certs' is specified, validate the server cert against it. If 'ssl_version' is specified, use it in the connection attempt.
get_server_certificate
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ssl.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ssl.py
MIT
def sslwrap_simple(sock, keyfile=None, certfile=None): """A replacement for the old socket.ssl function. Designed for compability with Python 2.5 and earlier. Will disappear in Python 3.0.""" if hasattr(sock, "_sock"): sock = sock._sock ctx = SSLContext(PROTOCOL_SSLv23) if keyfile or certfile: ctx.load_cert_chain(certfile, keyfile) ssl_sock = ctx._wrap_socket(sock, server_side=False) try: sock.getpeername() except socket_error: # no, no connection yet pass else: # yes, do the handshake ssl_sock.do_handshake() return ssl_sock
A replacement for the old socket.ssl function. Designed for compability with Python 2.5 and earlier. Will disappear in Python 3.0.
sslwrap_simple
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/ssl.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/ssl.py
MIT
def maketrans(fromstr, tostr): """maketrans(frm, to) -> string Return a translation table (a string of 256 bytes long) suitable for use in string.translate. The strings frm and to must be of the same length. """ if len(fromstr) != len(tostr): raise ValueError, "maketrans arguments must have same length" global _idmapL if not _idmapL: _idmapL = list(_idmap) L = _idmapL[:] fromstr = map(ord, fromstr) for i in range(len(fromstr)): L[fromstr[i]] = tostr[i] return ''.join(L)
maketrans(frm, to) -> string Return a translation table (a string of 256 bytes long) suitable for use in string.translate. The strings frm and to must be of the same length.
maketrans
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/string.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/string.py
MIT
def zfill(x, width): """zfill(x, width) -> string Pad a numeric string x with zeros on the left, to fill a field of the specified width. The string x is never truncated. """ if not isinstance(x, basestring): x = repr(x) return x.zfill(width)
zfill(x, width) -> string Pad a numeric string x with zeros on the left, to fill a field of the specified width. The string x is never truncated.
zfill
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/string.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/string.py
MIT
def translate(s, table, deletions=""): """translate(s,table [,deletions]) -> string Return a copy of the string s, where all characters occurring in the optional argument deletions are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256. The deletions argument is not allowed for Unicode strings. """ if deletions or table is None: return s.translate(table, deletions) else: # Add s[:0] so that if s is Unicode and table is an 8-bit string, # table is converted to Unicode. This means that table *cannot* # be a dictionary -- for that feature, use u.translate() directly. return s.translate(table + s[:0])
translate(s,table [,deletions]) -> string Return a copy of the string s, where all characters occurring in the optional argument deletions are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256. The deletions argument is not allowed for Unicode strings.
translate
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/string.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/string.py
MIT
def next(self): """A file object is its own iterator, for example iter(f) returns f (unless f is closed). When a file is used as an iterator, typically in a for loop (for example, for line in f: print line), the next() method is called repeatedly. This method returns the next input line, or raises StopIteration when EOF is hit. """ _complain_ifclosed(self.closed) r = self.readline() if not r: raise StopIteration return r
A file object is its own iterator, for example iter(f) returns f (unless f is closed). When a file is used as an iterator, typically in a for loop (for example, for line in f: print line), the next() method is called repeatedly. This method returns the next input line, or raises StopIteration when EOF is hit.
next
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/StringIO.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/StringIO.py
MIT
def seek(self, pos, mode = 0): """Set the file's current position. The mode argument is optional and defaults to 0 (absolute file positioning); other values are 1 (seek relative to the current position) and 2 (seek relative to the file's end). There is no return value. """ _complain_ifclosed(self.closed) if self.buflist: self.buf += ''.join(self.buflist) self.buflist = [] if mode == 1: pos += self.pos elif mode == 2: pos += self.len self.pos = max(0, pos)
Set the file's current position. The mode argument is optional and defaults to 0 (absolute file positioning); other values are 1 (seek relative to the current position) and 2 (seek relative to the file's end). There is no return value.
seek
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/StringIO.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/StringIO.py
MIT
def readline(self, length=None): r"""Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. An empty string is returned only when EOF is encountered immediately. Note: Unlike stdio's fgets(), the returned string contains null characters ('\0') if they occurred in the input. """ _complain_ifclosed(self.closed) if self.buflist: self.buf += ''.join(self.buflist) self.buflist = [] i = self.buf.find('\n', self.pos) if i < 0: newpos = self.len else: newpos = i+1 if length is not None and length >= 0: if self.pos + length < newpos: newpos = self.pos + length r = self.buf[self.pos:newpos] self.pos = newpos return r
Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned. An empty string is returned only when EOF is encountered immediately. Note: Unlike stdio's fgets(), the returned string contains null characters ('\0') if they occurred in the input.
readline
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/StringIO.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/StringIO.py
MIT
def readlines(self, sizehint = 0): """Read until EOF using readline() and return a list containing the lines thus read. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (or more to accommodate a final whole line). """ total = 0 lines = [] line = self.readline() while line: lines.append(line) total += len(line) if 0 < sizehint <= total: break line = self.readline() return lines
Read until EOF using readline() and return a list containing the lines thus read. If the optional sizehint argument is present, instead of reading up to EOF, whole lines totalling approximately sizehint bytes (or more to accommodate a final whole line).
readlines
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/StringIO.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/StringIO.py
MIT
def truncate(self, size=None): """Truncate the file's size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position. The current file position is not changed unless the position is beyond the new file size. If the specified size exceeds the file's current size, the file remains unchanged. """ _complain_ifclosed(self.closed) if size is None: size = self.pos elif size < 0: raise IOError(EINVAL, "Negative size not allowed") elif size < self.pos: self.pos = size self.buf = self.getvalue()[:size] self.len = size
Truncate the file's size. If the optional size argument is present, the file is truncated to (at most) that size. The size defaults to the current position. The current file position is not changed unless the position is beyond the new file size. If the specified size exceeds the file's current size, the file remains unchanged.
truncate
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/StringIO.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/StringIO.py
MIT
def write(self, s): """Write a string to the file. There is no return value. """ _complain_ifclosed(self.closed) if not s: return # Force s to be a string or unicode if not isinstance(s, basestring): s = str(s) spos = self.pos slen = self.len if spos == slen: self.buflist.append(s) self.len = self.pos = spos + len(s) return if spos > slen: self.buflist.append('\0'*(spos - slen)) slen = spos newpos = spos + len(s) if spos < slen: if self.buflist: self.buf += ''.join(self.buflist) self.buflist = [self.buf[:spos], s, self.buf[newpos:]] self.buf = '' if newpos > slen: slen = newpos else: self.buflist.append(s) slen = newpos self.len = slen self.pos = newpos
Write a string to the file. There is no return value.
write
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/StringIO.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/StringIO.py
MIT
def writelines(self, iterable): """Write a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings. There is no return value. (The name is intended to match readlines(); writelines() does not add line separators.) """ write = self.write for line in iterable: write(line)
Write a sequence of strings to the file. The sequence can be any iterable object producing strings, typically a list of strings. There is no return value. (The name is intended to match readlines(); writelines() does not add line separators.)
writelines
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/StringIO.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/StringIO.py
MIT
def getvalue(self): """ Retrieve the entire contents of the "file" at any time before the StringIO object's close() method is called. The StringIO object can accept either Unicode or 8-bit strings, but mixing the two may take some care. If both are used, 8-bit strings that cannot be interpreted as 7-bit ASCII (that use the 8th bit) will cause a UnicodeError to be raised when getvalue() is called. """ _complain_ifclosed(self.closed) if self.buflist: self.buf += ''.join(self.buflist) self.buflist = [] return self.buf
Retrieve the entire contents of the "file" at any time before the StringIO object's close() method is called. The StringIO object can accept either Unicode or 8-bit strings, but mixing the two may take some care. If both are used, 8-bit strings that cannot be interpreted as 7-bit ASCII (that use the 8th bit) will cause a UnicodeError to be raised when getvalue() is called.
getvalue
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/StringIO.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/StringIO.py
MIT
def atof(s): """atof(s) -> float Return the floating point number represented by the string s. """ if type(s) == _StringType: return _float(s) else: raise TypeError('argument 1: expected string, %s found' % type(s).__name__)
atof(s) -> float Return the floating point number represented by the string s.
atof
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/stringold.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/stringold.py
MIT
def atoi(*args): """atoi(s [,base]) -> int Return the integer represented by the string s in the given base, which defaults to 10. The string s must consist of one or more digits, possibly preceded by a sign. If base is 0, it is chosen from the leading characters of s, 0 for octal, 0x or 0X for hexadecimal. If base is 16, a preceding 0x or 0X is accepted. """ try: s = args[0] except IndexError: raise TypeError('function requires at least 1 argument: %d given' % len(args)) # Don't catch type error resulting from too many arguments to int(). The # error message isn't compatible but the error type is, and this function # is complicated enough already. if type(s) == _StringType: return _apply(_int, args) else: raise TypeError('argument 1: expected string, %s found' % type(s).__name__)
atoi(s [,base]) -> int Return the integer represented by the string s in the given base, which defaults to 10. The string s must consist of one or more digits, possibly preceded by a sign. If base is 0, it is chosen from the leading characters of s, 0 for octal, 0x or 0X for hexadecimal. If base is 16, a preceding 0x or 0X is accepted.
atoi
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/stringold.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/stringold.py
MIT
def atol(*args): """atol(s [,base]) -> long Return the long integer represented by the string s in the given base, which defaults to 10. The string s must consist of one or more digits, possibly preceded by a sign. If base is 0, it is chosen from the leading characters of s, 0 for octal, 0x or 0X for hexadecimal. If base is 16, a preceding 0x or 0X is accepted. A trailing L or l is not accepted, unless base is 0. """ try: s = args[0] except IndexError: raise TypeError('function requires at least 1 argument: %d given' % len(args)) # Don't catch type error resulting from too many arguments to long(). The # error message isn't compatible but the error type is, and this function # is complicated enough already. if type(s) == _StringType: return _apply(_long, args) else: raise TypeError('argument 1: expected string, %s found' % type(s).__name__)
atol(s [,base]) -> long Return the long integer represented by the string s in the given base, which defaults to 10. The string s must consist of one or more digits, possibly preceded by a sign. If base is 0, it is chosen from the leading characters of s, 0 for octal, 0x or 0X for hexadecimal. If base is 16, a preceding 0x or 0X is accepted. A trailing L or l is not accepted, unless base is 0.
atol
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/stringold.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/stringold.py
MIT
def ljust(s, width): """ljust(s, width) -> string Return a left-justified version of s, in a field of the specified width, padded with spaces as needed. The string is never truncated. """ n = width - len(s) if n <= 0: return s return s + ' '*n
ljust(s, width) -> string Return a left-justified version of s, in a field of the specified width, padded with spaces as needed. The string is never truncated.
ljust
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/stringold.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/stringold.py
MIT
def rjust(s, width): """rjust(s, width) -> string Return a right-justified version of s, in a field of the specified width, padded with spaces as needed. The string is never truncated. """ n = width - len(s) if n <= 0: return s return ' '*n + s
rjust(s, width) -> string Return a right-justified version of s, in a field of the specified width, padded with spaces as needed. The string is never truncated.
rjust
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/stringold.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/stringold.py
MIT
def center(s, width): """center(s, width) -> string Return a center version of s, in a field of the specified width. padded with spaces as needed. The string is never truncated. """ n = width - len(s) if n <= 0: return s half = n/2 if n%2 and width%2: # This ensures that center(center(s, i), j) = center(s, j) half = half+1 return ' '*half + s + ' '*(n-half)
center(s, width) -> string Return a center version of s, in a field of the specified width. padded with spaces as needed. The string is never truncated.
center
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/stringold.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/stringold.py
MIT
def zfill(x, width): """zfill(x, width) -> string Pad a numeric string x with zeros on the left, to fill a field of the specified width. The string x is never truncated. """ if type(x) == type(''): s = x else: s = repr(x) n = len(s) if n >= width: return s sign = '' if s[0] in ('-', '+'): sign, s = s[0], s[1:] return sign + '0'*(width-n) + s
zfill(x, width) -> string Pad a numeric string x with zeros on the left, to fill a field of the specified width. The string x is never truncated.
zfill
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/stringold.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/stringold.py
MIT
def expandtabs(s, tabsize=8): """expandtabs(s [,tabsize]) -> string Return a copy of the string s with all tab characters replaced by the appropriate number of spaces, depending on the current column, and the tabsize (default 8). """ res = line = '' for c in s: if c == '\t': c = ' '*(tabsize - len(line) % tabsize) line = line + c if c == '\n': res = res + line line = '' return res + line
expandtabs(s [,tabsize]) -> string Return a copy of the string s with all tab characters replaced by the appropriate number of spaces, depending on the current column, and the tabsize (default 8).
expandtabs
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/stringold.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/stringold.py
MIT
def maketrans(fromstr, tostr): """maketrans(frm, to) -> string Return a translation table (a string of 256 bytes long) suitable for use in string.translate. The strings frm and to must be of the same length. """ if len(fromstr) != len(tostr): raise ValueError, "maketrans arguments must have same length" global _idmapL if not _idmapL: _idmapL = list(_idmap) L = _idmapL[:] fromstr = map(ord, fromstr) for i in range(len(fromstr)): L[fromstr[i]] = tostr[i] return join(L, "")
maketrans(frm, to) -> string Return a translation table (a string of 256 bytes long) suitable for use in string.translate. The strings frm and to must be of the same length.
maketrans
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/stringold.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/stringold.py
MIT
def _args_from_interpreter_flags(): """Return a list of command-line arguments reproducing the current settings in sys.flags and sys.warnoptions.""" flag_opt_map = { 'debug': 'd', # 'inspect': 'i', # 'interactive': 'i', 'optimize': 'O', 'dont_write_bytecode': 'B', 'no_user_site': 's', 'no_site': 'S', 'ignore_environment': 'E', 'verbose': 'v', 'bytes_warning': 'b', 'py3k_warning': '3', } args = [] for flag, opt in flag_opt_map.items(): v = getattr(sys.flags, flag) if v > 0: args.append('-' + opt * v) if getattr(sys.flags, 'hash_randomization') != 0: args.append('-R') for opt in sys.warnoptions: args.append('-W' + opt) return args
Return a list of command-line arguments reproducing the current settings in sys.flags and sys.warnoptions.
_args_from_interpreter_flags
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/subprocess.py
MIT
def check_call(*popenargs, **kwargs): """Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute. The arguments are the same as for the Popen constructor. Example: check_call(["ls", "-l"]) """ retcode = call(*popenargs, **kwargs) if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] raise CalledProcessError(retcode, cmd) return 0
Run command with arguments. Wait for command to complete. If the exit code was zero then return, otherwise raise CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute. The arguments are the same as for the Popen constructor. Example: check_call(["ls", "-l"])
check_call
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/subprocess.py
MIT
def check_output(*popenargs, **kwargs): r"""Run command with arguments and return its output as a byte string. If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute. The arguments are the same as for the Popen constructor. Example: >>> check_output(["ls", "-l", "/dev/null"]) 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' The stdout argument is not allowed as it is used internally. To capture standard error in the result, use stderr=STDOUT. >>> check_output(["/bin/sh", "-c", ... "ls -l non_existent_file ; exit 0"], ... stderr=STDOUT) 'ls: non_existent_file: No such file or directory\n' """ if 'stdout' in kwargs: raise ValueError('stdout argument not allowed, it will be overridden.') process = Popen(stdout=PIPE, *popenargs, **kwargs) output, unused_err = process.communicate() retcode = process.poll() if retcode: cmd = kwargs.get("args") if cmd is None: cmd = popenargs[0] raise CalledProcessError(retcode, cmd, output=output) return output
Run command with arguments and return its output as a byte string. If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute. The arguments are the same as for the Popen constructor. Example: >>> check_output(["ls", "-l", "/dev/null"]) 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n' The stdout argument is not allowed as it is used internally. To capture standard error in the result, use stderr=STDOUT. >>> check_output(["/bin/sh", "-c", ... "ls -l non_existent_file ; exit 0"], ... stderr=STDOUT) 'ls: non_existent_file: No such file or directory\n'
check_output
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/subprocess.py
MIT
def communicate(self, input=None): """Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr).""" # Optimization: If we are only using one pipe, or no pipe at # all, using select() or threads is unnecessary. if [self.stdin, self.stdout, self.stderr].count(None) >= 2: stdout = None stderr = None if self.stdin: if input: try: self.stdin.write(input) except IOError as e: if e.errno != errno.EPIPE and e.errno != errno.EINVAL: raise self.stdin.close() elif self.stdout: stdout = _eintr_retry_call(self.stdout.read) self.stdout.close() elif self.stderr: stderr = _eintr_retry_call(self.stderr.read) self.stderr.close() self.wait() return (stdout, stderr) return self._communicate(input)
Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child. communicate() returns a tuple (stdout, stderr).
communicate
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/subprocess.py
MIT
def _get_handles(self, stdin, stdout, stderr): """Construct and return tuple with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite """ to_close = set() if stdin is None and stdout is None and stderr is None: return (None, None, None, None, None, None), to_close p2cread, p2cwrite = None, None c2pread, c2pwrite = None, None errread, errwrite = None, None if stdin is None: p2cread = _subprocess.GetStdHandle(_subprocess.STD_INPUT_HANDLE) if p2cread is None: p2cread, _ = _subprocess.CreatePipe(None, 0) elif stdin == PIPE: p2cread, p2cwrite = _subprocess.CreatePipe(None, 0) elif isinstance(stdin, int): p2cread = msvcrt.get_osfhandle(stdin) else: # Assuming file-like object p2cread = msvcrt.get_osfhandle(stdin.fileno()) p2cread = self._make_inheritable(p2cread) # We just duplicated the handle, it has to be closed at the end to_close.add(p2cread) if stdin == PIPE: to_close.add(p2cwrite) if stdout is None: c2pwrite = _subprocess.GetStdHandle(_subprocess.STD_OUTPUT_HANDLE) if c2pwrite is None: _, c2pwrite = _subprocess.CreatePipe(None, 0) elif stdout == PIPE: c2pread, c2pwrite = _subprocess.CreatePipe(None, 0) elif isinstance(stdout, int): c2pwrite = msvcrt.get_osfhandle(stdout) else: # Assuming file-like object c2pwrite = msvcrt.get_osfhandle(stdout.fileno()) c2pwrite = self._make_inheritable(c2pwrite) # We just duplicated the handle, it has to be closed at the end to_close.add(c2pwrite) if stdout == PIPE: to_close.add(c2pread) if stderr is None: errwrite = _subprocess.GetStdHandle(_subprocess.STD_ERROR_HANDLE) if errwrite is None: _, errwrite = _subprocess.CreatePipe(None, 0) elif stderr == PIPE: errread, errwrite = _subprocess.CreatePipe(None, 0) elif stderr == STDOUT: errwrite = c2pwrite elif isinstance(stderr, int): errwrite = msvcrt.get_osfhandle(stderr) else: # Assuming file-like object errwrite = msvcrt.get_osfhandle(stderr.fileno()) errwrite = self._make_inheritable(errwrite) # We just duplicated the handle, it has to be closed at the end to_close.add(errwrite) if stderr == PIPE: to_close.add(errread) return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite), to_close
Construct and return tuple with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
_get_handles
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/subprocess.py
MIT
def _make_inheritable(self, handle): """Return a duplicate of handle, which is inheritable""" return _subprocess.DuplicateHandle(_subprocess.GetCurrentProcess(), handle, _subprocess.GetCurrentProcess(), 0, 1, _subprocess.DUPLICATE_SAME_ACCESS)
Return a duplicate of handle, which is inheritable
_make_inheritable
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/subprocess.py
MIT
def _find_w9xpopen(self): """Find and return absolut path to w9xpopen.exe""" w9xpopen = os.path.join( os.path.dirname(_subprocess.GetModuleFileName(0)), "w9xpopen.exe") if not os.path.exists(w9xpopen): # Eeek - file-not-found - possibly an embedding # situation - see if we can locate it in sys.exec_prefix w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix), "w9xpopen.exe") if not os.path.exists(w9xpopen): raise RuntimeError("Cannot locate w9xpopen.exe, which is " "needed for Popen to work with your " "shell or platform.") return w9xpopen
Find and return absolut path to w9xpopen.exe
_find_w9xpopen
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/subprocess.py
MIT
def _internal_poll(self, _deadstate=None, _WaitForSingleObject=_subprocess.WaitForSingleObject, _WAIT_OBJECT_0=_subprocess.WAIT_OBJECT_0, _GetExitCodeProcess=_subprocess.GetExitCodeProcess): """Check if child process has terminated. Returns returncode attribute. This method is called by __del__, so it can only refer to objects in its local scope. """ if self.returncode is None: if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0: self.returncode = _GetExitCodeProcess(self._handle) return self.returncode
Check if child process has terminated. Returns returncode attribute. This method is called by __del__, so it can only refer to objects in its local scope.
_internal_poll
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/subprocess.py
MIT
def wait(self): """Wait for child process to terminate. Returns returncode attribute.""" if self.returncode is None: _subprocess.WaitForSingleObject(self._handle, _subprocess.INFINITE) self.returncode = _subprocess.GetExitCodeProcess(self._handle) return self.returncode
Wait for child process to terminate. Returns returncode attribute.
wait
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/subprocess.py
MIT
def _get_handles(self, stdin, stdout, stderr): """Construct and return tuple with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite """ to_close = set() p2cread, p2cwrite = None, None c2pread, c2pwrite = None, None errread, errwrite = None, None if stdin is None: pass elif stdin == PIPE: p2cread, p2cwrite = self.pipe_cloexec() to_close.update((p2cread, p2cwrite)) elif isinstance(stdin, int): p2cread = stdin else: # Assuming file-like object p2cread = stdin.fileno() if stdout is None: pass elif stdout == PIPE: c2pread, c2pwrite = self.pipe_cloexec() to_close.update((c2pread, c2pwrite)) elif isinstance(stdout, int): c2pwrite = stdout else: # Assuming file-like object c2pwrite = stdout.fileno() if stderr is None: pass elif stderr == PIPE: errread, errwrite = self.pipe_cloexec() to_close.update((errread, errwrite)) elif stderr == STDOUT: if c2pwrite is not None: errwrite = c2pwrite else: # child's stdout is not set, use parent's stdout errwrite = sys.__stdout__.fileno() elif isinstance(stderr, int): errwrite = stderr else: # Assuming file-like object errwrite = stderr.fileno() return (p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite), to_close
Construct and return tuple with IO objects: p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
_get_handles
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/subprocess.py
MIT
def pipe_cloexec(self): """Create a pipe with FDs set CLOEXEC.""" # Pipes' FDs are set CLOEXEC by default because we don't want them # to be inherited by other subprocesses: the CLOEXEC flag is removed # from the child's FDs by _dup2(), between fork() and exec(). # This is not atomic: we would need the pipe2() syscall for that. r, w = os.pipe() self._set_cloexec_flag(r) self._set_cloexec_flag(w) return r, w
Create a pipe with FDs set CLOEXEC.
pipe_cloexec
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/subprocess.py
MIT
def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid, _WNOHANG=os.WNOHANG, _os_error=os.error, _ECHILD=errno.ECHILD): """Check if child process has terminated. Returns returncode attribute. This method is called by __del__, so it cannot reference anything outside of the local scope (nor can any methods it calls). """ if self.returncode is None: try: pid, sts = _waitpid(self.pid, _WNOHANG) if pid == self.pid: self._handle_exitstatus(sts) except _os_error as e: if _deadstate is not None: self.returncode = _deadstate if e.errno == _ECHILD: # This happens if SIGCLD is set to be ignored or # waiting for child processes has otherwise been # disabled for our process. This child is dead, we # can't get the status. # http://bugs.python.org/issue15756 self.returncode = 0 return self.returncode
Check if child process has terminated. Returns returncode attribute. This method is called by __del__, so it cannot reference anything outside of the local scope (nor can any methods it calls).
_internal_poll
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/subprocess.py
MIT
def wait(self): """Wait for child process to terminate. Returns returncode attribute.""" while self.returncode is None: try: pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0) except OSError as e: if e.errno != errno.ECHILD: raise # This happens if SIGCLD is set to be ignored or waiting # for child processes has otherwise been disabled for our # process. This child is dead, we can't get the status. pid = self.pid sts = 0 # Check the pid and loop as waitpid has been known to return # 0 even without WNOHANG in odd situations. issue14396. if pid == self.pid: self._handle_exitstatus(sts) return self.returncode
Wait for child process to terminate. Returns returncode attribute.
wait
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/subprocess.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/subprocess.py
MIT
def gethdr(fp): """Read a sound header from an open file.""" if fp.read(4) != MAGIC: raise error, 'gethdr: bad magic word' hdr_size = get_long_be(fp.read(4)) data_size = get_long_be(fp.read(4)) encoding = get_long_be(fp.read(4)) sample_rate = get_long_be(fp.read(4)) channels = get_long_be(fp.read(4)) excess = hdr_size - 24 if excess < 0: raise error, 'gethdr: bad hdr_size' if excess > 0: info = fp.read(excess) else: info = '' return (data_size, encoding, sample_rate, channels, info)
Read a sound header from an open file.
gethdr
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/sunaudio.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/sunaudio.py
MIT
def printhdr(file): """Read and print the sound header of a named file.""" hdr = gethdr(open(file, 'r')) data_size, encoding, sample_rate, channels, info = hdr while info[-1:] == '\0': info = info[:-1] print 'File name: ', file print 'Data size: ', data_size print 'Encoding: ', encoding print 'Sample rate:', sample_rate print 'Channels: ', channels print 'Info: ', repr(info)
Read and print the sound header of a named file.
printhdr
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/sunaudio.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/sunaudio.py
MIT
def get_namespace(self): """Returns the single namespace bound to this name. Raises ValueError if the name is bound to multiple namespaces. """ if len(self.__namespaces) != 1: raise ValueError, "name is bound to multiple namespaces" return self.__namespaces[0]
Returns the single namespace bound to this name. Raises ValueError if the name is bound to multiple namespaces.
get_namespace
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/symtable.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/symtable.py
MIT
def _parse_makefile(filename, vars=None): """Parse a Makefile-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ import re # Regexes needed for parsing Makefile (and similar syntaxes, # like old-style Setup files). _variable_rx = re.compile("([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)") _findvar1_rx = re.compile(r"\$\(([A-Za-z][A-Za-z0-9_]*)\)") _findvar2_rx = re.compile(r"\${([A-Za-z][A-Za-z0-9_]*)}") if vars is None: vars = {} done = {} notdone = {} with open(filename) as f: lines = f.readlines() for line in lines: if line.startswith('#') or line.strip() == '': continue m = _variable_rx.match(line) if m: n, v = m.group(1, 2) v = v.strip() # `$$' is a literal `$' in make tmpv = v.replace('$$', '') if "$" in tmpv: notdone[n] = v else: try: v = int(v) except ValueError: # insert literal `$' done[n] = v.replace('$$', '$') else: done[n] = v # do variable interpolation here while notdone: for name in notdone.keys(): value = notdone[name] m = _findvar1_rx.search(value) or _findvar2_rx.search(value) if m: n = m.group(1) found = True if n in done: item = str(done[n]) elif n in notdone: # get it on a subsequent round found = False elif n in os.environ: # do it like make: fall back to environment item = os.environ[n] else: done[n] = item = "" if found: after = value[m.end():] value = value[:m.start()] + item + after if "$" in after: notdone[name] = value else: try: value = int(value) except ValueError: done[name] = value.strip() else: done[name] = value del notdone[name] else: # bogus variable reference; just drop it since we can't deal del notdone[name] # strip spurious spaces for k, v in done.items(): if isinstance(v, str): done[k] = v.strip() # save the results in the global dictionary vars.update(done) return vars
Parse a Makefile-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary.
_parse_makefile
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/sysconfig.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/sysconfig.py
MIT
def get_makefile_filename(): """Return the path of the Makefile.""" if _PYTHON_BUILD: return os.path.join(_PROJECT_BASE, "Makefile") return os.path.join(get_path('platstdlib'), "config", "Makefile")
Return the path of the Makefile.
get_makefile_filename
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/sysconfig.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/sysconfig.py
MIT
def _generate_posix_vars(): """Generate the Python module containing build-time variables.""" import pprint vars = {} # load the installed Makefile: makefile = get_makefile_filename() try: _parse_makefile(makefile, vars) except IOError, e: msg = "invalid Python installation: unable to open %s" % makefile if hasattr(e, "strerror"): msg = msg + " (%s)" % e.strerror raise IOError(msg) # load the installed pyconfig.h: config_h = get_config_h_filename() try: with open(config_h) as f: parse_config_h(f, vars) except IOError, e: msg = "invalid Python installation: unable to open %s" % config_h if hasattr(e, "strerror"): msg = msg + " (%s)" % e.strerror raise IOError(msg) # On AIX, there are wrong paths to the linker scripts in the Makefile # -- these paths are relative to the Python source, but when installed # the scripts are in another directory. if _PYTHON_BUILD: vars['LDSHARED'] = vars['BLDSHARED'] # There's a chicken-and-egg situation on OS X with regards to the # _sysconfigdata module after the changes introduced by #15298: # get_config_vars() is called by get_platform() as part of the # `make pybuilddir.txt` target -- which is a precursor to the # _sysconfigdata.py module being constructed. Unfortunately, # get_config_vars() eventually calls _init_posix(), which attempts # to import _sysconfigdata, which we won't have built yet. In order # for _init_posix() to work, if we're on Darwin, just mock up the # _sysconfigdata module manually and populate it with the build vars. # This is more than sufficient for ensuring the subsequent call to # get_platform() succeeds. name = '_sysconfigdata' if 'darwin' in sys.platform: import imp module = imp.new_module(name) module.build_time_vars = vars sys.modules[name] = module pybuilddir = 'build/lib.%s-%s' % (get_platform(), sys.version[:3]) if hasattr(sys, "gettotalrefcount"): pybuilddir += '-pydebug' try: os.makedirs(pybuilddir) except OSError: pass destfile = os.path.join(pybuilddir, name + '.py') with open(destfile, 'wb') as f: f.write('# system configuration generated and used by' ' the sysconfig module\n') f.write('build_time_vars = ') pprint.pprint(vars, stream=f) # Create file used for sys.path fixup -- see Modules/getpath.c with open('pybuilddir.txt', 'w') as f: f.write(pybuilddir)
Generate the Python module containing build-time variables.
_generate_posix_vars
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/sysconfig.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/sysconfig.py
MIT
def _init_posix(vars): """Initialize the module as appropriate for POSIX systems.""" # _sysconfigdata is generated at build time, see _generate_posix_vars() from _sysconfigdata import build_time_vars vars.update(build_time_vars)
Initialize the module as appropriate for POSIX systems.
_init_posix
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/sysconfig.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/sysconfig.py
MIT
def _init_non_posix(vars): """Initialize the module as appropriate for NT""" # set basic install directories vars['LIBDEST'] = get_path('stdlib') vars['BINLIBDEST'] = get_path('platstdlib') vars['INCLUDEPY'] = get_path('include') vars['SO'] = '.pyd' vars['EXE'] = '.exe' vars['VERSION'] = _PY_VERSION_SHORT_NO_DOT vars['BINDIR'] = os.path.dirname(_safe_realpath(sys.executable))
Initialize the module as appropriate for NT
_init_non_posix
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/sysconfig.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/sysconfig.py
MIT
def parse_config_h(fp, vars=None): """Parse a config.h-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary. """ import re if vars is None: vars = {} define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n") undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n") while True: line = fp.readline() if not line: break m = define_rx.match(line) if m: n, v = m.group(1, 2) try: v = int(v) except ValueError: pass vars[n] = v else: m = undef_rx.match(line) if m: vars[m.group(1)] = 0 return vars
Parse a config.h-style file. A dictionary containing name/value pairs is returned. If an optional dictionary is passed in as the second argument, it is used instead of a new dictionary.
parse_config_h
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/sysconfig.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/sysconfig.py
MIT
def get_scheme_names(): """Returns a tuple containing the schemes names.""" schemes = _INSTALL_SCHEMES.keys() schemes.sort() return tuple(schemes)
Returns a tuple containing the schemes names.
get_scheme_names
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/sysconfig.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/sysconfig.py
MIT
def get_paths(scheme=_get_default_scheme(), vars=None, expand=True): """Returns a mapping containing an install scheme. ``scheme`` is the install scheme name. If not provided, it will return the default scheme for the current platform. """ if expand: return _expand_vars(scheme, vars) else: return _INSTALL_SCHEMES[scheme]
Returns a mapping containing an install scheme. ``scheme`` is the install scheme name. If not provided, it will return the default scheme for the current platform.
get_paths
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/sysconfig.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/sysconfig.py
MIT
def get_config_vars(*args): """With no arguments, return a dictionary of all configuration variables relevant for the current platform. On Unix, this means every variable defined in Python's installed Makefile; On Windows and Mac OS it's a much smaller set. With arguments, return a list of values that result from looking up each argument in the configuration variable dictionary. """ import re global _CONFIG_VARS if _CONFIG_VARS is None: _CONFIG_VARS = {} # Normalized versions of prefix and exec_prefix are handy to have; # in fact, these are the standard versions used most places in the # Distutils. _CONFIG_VARS['prefix'] = _PREFIX _CONFIG_VARS['exec_prefix'] = _EXEC_PREFIX _CONFIG_VARS['py_version'] = _PY_VERSION _CONFIG_VARS['py_version_short'] = _PY_VERSION_SHORT _CONFIG_VARS['py_version_nodot'] = _PY_VERSION[0] + _PY_VERSION[2] _CONFIG_VARS['base'] = _PREFIX _CONFIG_VARS['platbase'] = _EXEC_PREFIX _CONFIG_VARS['projectbase'] = _PROJECT_BASE if os.name in ('nt', 'os2'): _init_non_posix(_CONFIG_VARS) if os.name == 'posix': _init_posix(_CONFIG_VARS) # Setting 'userbase' is done below the call to the # init function to enable using 'get_config_var' in # the init-function. _CONFIG_VARS['userbase'] = _getuserbase() if 'srcdir' not in _CONFIG_VARS: _CONFIG_VARS['srcdir'] = _PROJECT_BASE # Convert srcdir into an absolute path if it appears necessary. # Normally it is relative to the build directory. However, during # testing, for example, we might be running a non-installed python # from a different directory. if _PYTHON_BUILD and os.name == "posix": base = _PROJECT_BASE try: cwd = os.getcwd() except OSError: cwd = None if (not os.path.isabs(_CONFIG_VARS['srcdir']) and base != cwd): # srcdir is relative and we are not in the same directory # as the executable. Assume executable is in the build # directory and make srcdir absolute. srcdir = os.path.join(base, _CONFIG_VARS['srcdir']) _CONFIG_VARS['srcdir'] = os.path.normpath(srcdir) # OS X platforms require special customization to handle # multi-architecture, multi-os-version installers if sys.platform == 'darwin': import _osx_support _osx_support.customize_config_vars(_CONFIG_VARS) if args: vals = [] for name in args: vals.append(_CONFIG_VARS.get(name)) return vals else: return _CONFIG_VARS
With no arguments, return a dictionary of all configuration variables relevant for the current platform. On Unix, this means every variable defined in Python's installed Makefile; On Windows and Mac OS it's a much smaller set. With arguments, return a list of values that result from looking up each argument in the configuration variable dictionary.
get_config_vars
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/sysconfig.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/sysconfig.py
MIT
def get_platform(): """Return a string that identifies the current platform. This is used mainly to distinguish platform-specific build directories and platform-specific built distributions. Typically includes the OS name and version and the architecture (as supplied by 'os.uname()'), although the exact information included depends on the OS; eg. for IRIX the architecture isn't particularly important (IRIX only runs on SGI hardware), but for Linux the kernel version isn't particularly important. Examples of returned values: linux-i586 linux-alpha (?) solaris-2.6-sun4u irix-5.3 irix64-6.2 Windows will return one of: win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc) win-ia64 (64bit Windows on Itanium) win32 (all others - specifically, sys.platform is returned) For other non-POSIX platforms, currently just returns 'sys.platform'. """ import re if os.name == 'nt': # sniff sys.version for architecture. prefix = " bit (" i = sys.version.find(prefix) if i == -1: return sys.platform j = sys.version.find(")", i) look = sys.version[i+len(prefix):j].lower() if look == 'amd64': return 'win-amd64' if look == 'itanium': return 'win-ia64' return sys.platform # Set for cross builds explicitly if "_PYTHON_HOST_PLATFORM" in os.environ: return os.environ["_PYTHON_HOST_PLATFORM"] if os.name != "posix" or not hasattr(os, 'uname'): # XXX what about the architecture? NT is Intel or Alpha, # Mac OS is M68k or PPC, etc. return sys.platform # Try to distinguish various flavours of Unix osname, host, release, version, machine = os.uname() # Convert the OS name to lowercase, remove '/' characters # (to accommodate BSD/OS), and translate spaces (for "Power Macintosh") osname = osname.lower().replace('/', '') machine = machine.replace(' ', '_') machine = machine.replace('/', '-') if osname[:5] == "linux": # At least on Linux/Intel, 'machine' is the processor -- # i386, etc. # XXX what about Alpha, SPARC, etc? return "%s-%s" % (osname, machine) elif osname[:5] == "sunos": if release[0] >= "5": # SunOS 5 == Solaris 2 osname = "solaris" release = "%d.%s" % (int(release[0]) - 3, release[2:]) # We can't use "platform.architecture()[0]" because a # bootstrap problem. We use a dict to get an error # if some suspicious happens. bitness = {2147483647:"32bit", 9223372036854775807:"64bit"} machine += ".%s" % bitness[sys.maxint] # fall through to standard osname-release-machine representation elif osname[:4] == "irix": # could be "irix64"! return "%s-%s" % (osname, release) elif osname[:3] == "aix": return "%s-%s.%s" % (osname, version, release) elif osname[:6] == "cygwin": osname = "cygwin" rel_re = re.compile (r'[\d.]+') m = rel_re.match(release) if m: release = m.group() elif osname[:6] == "darwin": import _osx_support osname, release, machine = _osx_support.get_platform_osx( get_config_vars(), osname, release, machine) return "%s-%s-%s" % (osname, release, machine)
Return a string that identifies the current platform. This is used mainly to distinguish platform-specific build directories and platform-specific built distributions. Typically includes the OS name and version and the architecture (as supplied by 'os.uname()'), although the exact information included depends on the OS; eg. for IRIX the architecture isn't particularly important (IRIX only runs on SGI hardware), but for Linux the kernel version isn't particularly important. Examples of returned values: linux-i586 linux-alpha (?) solaris-2.6-sun4u irix-5.3 irix64-6.2 Windows will return one of: win-amd64 (64bit Windows on AMD64 (aka x86_64, Intel64, EM64T, etc) win-ia64 (64bit Windows on Itanium) win32 (all others - specifically, sys.platform is returned) For other non-POSIX platforms, currently just returns 'sys.platform'.
get_platform
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/sysconfig.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/sysconfig.py
MIT
def check(file): """check(file_or_dir) If file_or_dir is a directory and not a symbolic link, then recursively descend the directory tree named by file_or_dir, checking all .py files along the way. If file_or_dir is an ordinary Python source file, it is checked for whitespace related problems. The diagnostic messages are written to standard output using the print statement. """ if os.path.isdir(file) and not os.path.islink(file): if verbose: print "%r: listing directory" % (file,) names = os.listdir(file) for name in names: fullname = os.path.join(file, name) if (os.path.isdir(fullname) and not os.path.islink(fullname) or os.path.normcase(name[-3:]) == ".py"): check(fullname) return try: f = open(file) except IOError, msg: errprint("%r: I/O Error: %s" % (file, msg)) return if verbose > 1: print "checking %r ..." % file try: process_tokens(tokenize.generate_tokens(f.readline)) except tokenize.TokenError, msg: errprint("%r: Token Error: %s" % (file, msg)) return except IndentationError, msg: errprint("%r: Indentation Error: %s" % (file, msg)) return except NannyNag, nag: badline = nag.get_lineno() line = nag.get_line() if verbose: print "%r: *** Line %d: trouble in tab city! ***" % (file, badline) print "offending line: %r" % (line,) print nag.get_msg() else: if ' ' in file: file = '"' + file + '"' if filename_only: print file else: print file, badline, repr(line) return if verbose: print "%r: Clean bill of health." % (file,)
check(file_or_dir) If file_or_dir is a directory and not a symbolic link, then recursively descend the directory tree named by file_or_dir, checking all .py files along the way. If file_or_dir is an ordinary Python source file, it is checked for whitespace related problems. The diagnostic messages are written to standard output using the print statement.
check
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tabnanny.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tabnanny.py
MIT
def nts(s): """Convert a null-terminated string field to a python string. """ # Use the string up to the first null char. p = s.find("\0") if p == -1: return s return s[:p]
Convert a null-terminated string field to a python string.
nts
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def nti(s): """Convert a number field to a python number. """ # There are two possible encodings for a number field, see # itn() below. if s[0] != chr(0200): try: n = int(nts(s).strip() or "0", 8) except ValueError: raise InvalidHeaderError("invalid header") else: n = 0L for i in xrange(len(s) - 1): n <<= 8 n += ord(s[i + 1]) return n
Convert a number field to a python number.
nti
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def itn(n, digits=8, format=DEFAULT_FORMAT): """Convert a python number to a number field. """ # POSIX 1003.1-1988 requires numbers to be encoded as a string of # octal digits followed by a null-byte, this allows values up to # (8**(digits-1))-1. GNU tar allows storing numbers greater than # that if necessary. A leading 0200 byte indicates this particular # encoding, the following digits-1 bytes are a big-endian # representation. This allows values up to (256**(digits-1))-1. if 0 <= n < 8 ** (digits - 1): s = "%0*o" % (digits - 1, n) + NUL else: if format != GNU_FORMAT or n >= 256 ** (digits - 1): raise ValueError("overflow in number field") if n < 0: # XXX We mimic GNU tar's behaviour with negative numbers, # this could raise OverflowError. n = struct.unpack("L", struct.pack("l", n))[0] s = "" for i in xrange(digits - 1): s = chr(n & 0377) + s n >>= 8 s = chr(0200) + s return s
Convert a python number to a number field.
itn
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def calc_chksums(buf): """Calculate the checksum for a member's header by summing up all characters except for the chksum field which is treated as if it was filled with spaces. According to the GNU tar sources, some tars (Sun and NeXT) calculate chksum with signed char, which will be different if there are chars in the buffer with the high bit set. So we calculate two checksums, unsigned and signed. """ unsigned_chksum = 256 + sum(struct.unpack("148B", buf[:148]) + struct.unpack("356B", buf[156:512])) signed_chksum = 256 + sum(struct.unpack("148b", buf[:148]) + struct.unpack("356b", buf[156:512])) return unsigned_chksum, signed_chksum
Calculate the checksum for a member's header by summing up all characters except for the chksum field which is treated as if it was filled with spaces. According to the GNU tar sources, some tars (Sun and NeXT) calculate chksum with signed char, which will be different if there are chars in the buffer with the high bit set. So we calculate two checksums, unsigned and signed.
calc_chksums
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def copyfileobj(src, dst, length=None): """Copy length bytes from fileobj src to fileobj dst. If length is None, copy the entire content. """ if length == 0: return if length is None: shutil.copyfileobj(src, dst) return BUFSIZE = 16 * 1024 blocks, remainder = divmod(length, BUFSIZE) for b in xrange(blocks): buf = src.read(BUFSIZE) if len(buf) < BUFSIZE: raise IOError("end of file reached") dst.write(buf) if remainder != 0: buf = src.read(remainder) if len(buf) < remainder: raise IOError("end of file reached") dst.write(buf) return
Copy length bytes from fileobj src to fileobj dst. If length is None, copy the entire content.
copyfileobj
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def filemode(mode): """Convert a file's mode to a string of the form -rwxrwxrwx. Used by TarFile.list() """ perm = [] for table in filemode_table: for bit, char in table: if mode & bit == bit: perm.append(char) break else: perm.append("-") return "".join(perm)
Convert a file's mode to a string of the form -rwxrwxrwx. Used by TarFile.list()
filemode
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def _init_write_gz(self): """Initialize for writing with gzip compression. """ self.cmp = self.zlib.compressobj(9, self.zlib.DEFLATED, -self.zlib.MAX_WBITS, self.zlib.DEF_MEM_LEVEL, 0) timestamp = struct.pack("<L", long(time.time())) self.__write("\037\213\010\010%s\002\377" % timestamp) if type(self.name) is unicode: self.name = self.name.encode("iso-8859-1", "replace") if self.name.endswith(".gz"): self.name = self.name[:-3] self.__write(self.name + NUL)
Initialize for writing with gzip compression.
_init_write_gz
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def __write(self, s): """Write string s to the stream if a whole new block is ready to be written. """ self.buf += s while len(self.buf) > self.bufsize: self.fileobj.write(self.buf[:self.bufsize]) self.buf = self.buf[self.bufsize:]
Write string s to the stream if a whole new block is ready to be written.
__write
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def close(self): """Close the _Stream object. No operation should be done on it afterwards. """ if self.closed: return self.closed = True try: if self.mode == "w" and self.comptype != "tar": self.buf += self.cmp.flush() if self.mode == "w" and self.buf: self.fileobj.write(self.buf) self.buf = "" if self.comptype == "gz": # The native zlib crc is an unsigned 32-bit integer, but # the Python wrapper implicitly casts that to a signed C # long. So, on a 32-bit box self.crc may "look negative", # while the same crc on a 64-bit box may "look positive". # To avoid irksome warnings from the `struct` module, force # it to look positive on all boxes. self.fileobj.write(struct.pack("<L", self.crc & 0xffffffffL)) self.fileobj.write(struct.pack("<L", self.pos & 0xffffFFFFL)) finally: if not self._extfileobj: self.fileobj.close()
Close the _Stream object. No operation should be done on it afterwards.
close
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def _init_read_gz(self): """Initialize for reading a gzip compressed fileobj. """ self.cmp = self.zlib.decompressobj(-self.zlib.MAX_WBITS) self.dbuf = "" # taken from gzip.GzipFile with some alterations if self.__read(2) != "\037\213": raise ReadError("not a gzip file") if self.__read(1) != "\010": raise CompressionError("unsupported compression method") flag = ord(self.__read(1)) self.__read(6) if flag & 4: xlen = ord(self.__read(1)) + 256 * ord(self.__read(1)) self.read(xlen) if flag & 8: while True: s = self.__read(1) if not s or s == NUL: break if flag & 16: while True: s = self.__read(1) if not s or s == NUL: break if flag & 2: self.__read(2)
Initialize for reading a gzip compressed fileobj.
_init_read_gz
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def seek(self, pos=0): """Set the stream's file pointer to pos. Negative seeking is forbidden. """ if pos - self.pos >= 0: blocks, remainder = divmod(pos - self.pos, self.bufsize) for i in xrange(blocks): self.read(self.bufsize) self.read(remainder) else: raise StreamError("seeking backwards is not allowed") return self.pos
Set the stream's file pointer to pos. Negative seeking is forbidden.
seek
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def read(self, size=None): """Return the next size number of bytes from the stream. If size is not defined, return all bytes of the stream up to EOF. """ if size is None: t = [] while True: buf = self._read(self.bufsize) if not buf: break t.append(buf) buf = "".join(t) else: buf = self._read(size) self.pos += len(buf) return buf
Return the next size number of bytes from the stream. If size is not defined, return all bytes of the stream up to EOF.
read
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def _read(self, size): """Return size bytes from the stream. """ if self.comptype == "tar": return self.__read(size) c = len(self.dbuf) t = [self.dbuf] while c < size: buf = self.__read(self.bufsize) if not buf: break try: buf = self.cmp.decompress(buf) except IOError: raise ReadError("invalid compressed data") t.append(buf) c += len(buf) t = "".join(t) self.dbuf = t[size:] return t[:size]
Return size bytes from the stream.
_read
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def __read(self, size): """Return size bytes from stream. If internal buffer is empty, read another block from the stream. """ c = len(self.buf) t = [self.buf] while c < size: buf = self.fileobj.read(self.bufsize) if not buf: break t.append(buf) c += len(buf) t = "".join(t) self.buf = t[size:] return t[:size]
Return size bytes from stream. If internal buffer is empty, read another block from the stream.
__read
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def readsparsesection(self, size): """Read a single section of a sparse file. """ section = self.sparse.find(self.position) if section is None: return "" size = min(size, section.offset + section.size - self.position) if isinstance(section, _data): realpos = section.realpos + self.position - section.offset self.fileobj.seek(self.offset + realpos) self.position += size return self.__read(size) else: self.position += size return NUL * size
Read a single section of a sparse file.
readsparsesection
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def read(self, size=None): """Read at most size bytes from the file. If size is not present or None, read all data until EOF is reached. """ if self.closed: raise ValueError("I/O operation on closed file") buf = "" if self.buffer: if size is None: buf = self.buffer self.buffer = "" else: buf = self.buffer[:size] self.buffer = self.buffer[size:] if size is None: buf += self.fileobj.read() else: buf += self.fileobj.read(size - len(buf)) self.position += len(buf) return buf
Read at most size bytes from the file. If size is not present or None, read all data until EOF is reached.
read
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def readline(self, size=-1): """Read one entire line from the file. If size is present and non-negative, return a string with at most that size, which may be an incomplete line. """ if self.closed: raise ValueError("I/O operation on closed file") if "\n" in self.buffer: pos = self.buffer.find("\n") + 1 else: buffers = [self.buffer] while True: buf = self.fileobj.read(self.blocksize) buffers.append(buf) if not buf or "\n" in buf: self.buffer = "".join(buffers) pos = self.buffer.find("\n") + 1 if pos == 0: # no newline found. pos = len(self.buffer) break if size != -1: pos = min(size, pos) buf = self.buffer[:pos] self.buffer = self.buffer[pos:] self.position += len(buf) return buf
Read one entire line from the file. If size is present and non-negative, return a string with at most that size, which may be an incomplete line.
readline
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def readlines(self): """Return a list with all remaining lines. """ result = [] while True: line = self.readline() if not line: break result.append(line) return result
Return a list with all remaining lines.
readlines
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def seek(self, pos, whence=os.SEEK_SET): """Seek to a position in the file. """ if self.closed: raise ValueError("I/O operation on closed file") if whence == os.SEEK_SET: self.position = min(max(pos, 0), self.size) elif whence == os.SEEK_CUR: if pos < 0: self.position = max(self.position + pos, 0) else: self.position = min(self.position + pos, self.size) elif whence == os.SEEK_END: self.position = max(min(self.size + pos, self.size), 0) else: raise ValueError("Invalid argument") self.buffer = "" self.fileobj.seek(self.position)
Seek to a position in the file.
seek
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def __iter__(self): """Get an iterator over the file's lines. """ while True: line = self.readline() if not line: break yield line
Get an iterator over the file's lines.
__iter__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def __init__(self, name=""): """Construct a TarInfo object. name is the optional name of the member. """ self.name = name # member name self.mode = 0644 # file permissions self.uid = 0 # user id self.gid = 0 # group id self.size = 0 # file size self.mtime = 0 # modification time self.chksum = 0 # header checksum self.type = REGTYPE # member type self.linkname = "" # link name self.uname = "" # user name self.gname = "" # group name self.devmajor = 0 # device major number self.devminor = 0 # device minor number self.offset = 0 # the tar header starts here self.offset_data = 0 # the file's data starts here self.pax_headers = {} # pax header information
Construct a TarInfo object. name is the optional name of the member.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def get_info(self, encoding, errors): """Return the TarInfo's attributes as a dictionary. """ info = { "name": self.name, "mode": self.mode & 07777, "uid": self.uid, "gid": self.gid, "size": self.size, "mtime": self.mtime, "chksum": self.chksum, "type": self.type, "linkname": self.linkname, "uname": self.uname, "gname": self.gname, "devmajor": self.devmajor, "devminor": self.devminor } if info["type"] == DIRTYPE and not info["name"].endswith("/"): info["name"] += "/" for key in ("name", "linkname", "uname", "gname"): if type(info[key]) is unicode: info[key] = info[key].encode(encoding, errors) return info
Return the TarInfo's attributes as a dictionary.
get_info
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def tobuf(self, format=DEFAULT_FORMAT, encoding=ENCODING, errors="strict"): """Return a tar header as a string of 512 byte blocks. """ info = self.get_info(encoding, errors) if format == USTAR_FORMAT: return self.create_ustar_header(info) elif format == GNU_FORMAT: return self.create_gnu_header(info) elif format == PAX_FORMAT: return self.create_pax_header(info, encoding, errors) else: raise ValueError("invalid format")
Return a tar header as a string of 512 byte blocks.
tobuf
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def create_ustar_header(self, info): """Return the object as a ustar header block. """ info["magic"] = POSIX_MAGIC if len(info["linkname"]) > LENGTH_LINK: raise ValueError("linkname is too long") if len(info["name"]) > LENGTH_NAME: info["prefix"], info["name"] = self._posix_split_name(info["name"]) return self._create_header(info, USTAR_FORMAT)
Return the object as a ustar header block.
create_ustar_header
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def create_gnu_header(self, info): """Return the object as a GNU header block sequence. """ info["magic"] = GNU_MAGIC buf = "" if len(info["linkname"]) > LENGTH_LINK: buf += self._create_gnu_long_header(info["linkname"], GNUTYPE_LONGLINK) if len(info["name"]) > LENGTH_NAME: buf += self._create_gnu_long_header(info["name"], GNUTYPE_LONGNAME) return buf + self._create_header(info, GNU_FORMAT)
Return the object as a GNU header block sequence.
create_gnu_header
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def create_pax_header(self, info, encoding, errors): """Return the object as a ustar header block. If it cannot be represented this way, prepend a pax extended header sequence with supplement information. """ info["magic"] = POSIX_MAGIC pax_headers = self.pax_headers.copy() # Test string fields for values that exceed the field length or cannot # be represented in ASCII encoding. for name, hname, length in ( ("name", "path", LENGTH_NAME), ("linkname", "linkpath", LENGTH_LINK), ("uname", "uname", 32), ("gname", "gname", 32)): if hname in pax_headers: # The pax header has priority. continue val = info[name].decode(encoding, errors) # Try to encode the string as ASCII. try: val.encode("ascii") except UnicodeEncodeError: pax_headers[hname] = val continue if len(info[name]) > length: pax_headers[hname] = val # Test number fields for values that exceed the field limit or values # that like to be stored as float. for name, digits in (("uid", 8), ("gid", 8), ("size", 12), ("mtime", 12)): if name in pax_headers: # The pax header has priority. Avoid overflow. info[name] = 0 continue val = info[name] if not 0 <= val < 8 ** (digits - 1) or isinstance(val, float): pax_headers[name] = unicode(val) info[name] = 0 # Create a pax extended header if necessary. if pax_headers: buf = self._create_pax_generic_header(pax_headers) else: buf = "" return buf + self._create_header(info, USTAR_FORMAT)
Return the object as a ustar header block. If it cannot be represented this way, prepend a pax extended header sequence with supplement information.
create_pax_header
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def _posix_split_name(self, name): """Split a name longer than 100 chars into a prefix and a name part. """ prefix = name[:LENGTH_PREFIX + 1] while prefix and prefix[-1] != "/": prefix = prefix[:-1] name = name[len(prefix):] prefix = prefix[:-1] if not prefix or len(name) > LENGTH_NAME: raise ValueError("name is too long") return prefix, name
Split a name longer than 100 chars into a prefix and a name part.
_posix_split_name
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def _create_header(info, format): """Return a header block. info is a dictionary with file information, format must be one of the *_FORMAT constants. """ parts = [ stn(info.get("name", ""), 100), itn(info.get("mode", 0) & 07777, 8, format), itn(info.get("uid", 0), 8, format), itn(info.get("gid", 0), 8, format), itn(info.get("size", 0), 12, format), itn(info.get("mtime", 0), 12, format), " ", # checksum field info.get("type", REGTYPE), stn(info.get("linkname", ""), 100), stn(info.get("magic", POSIX_MAGIC), 8), stn(info.get("uname", ""), 32), stn(info.get("gname", ""), 32), itn(info.get("devmajor", 0), 8, format), itn(info.get("devminor", 0), 8, format), stn(info.get("prefix", ""), 155) ] buf = struct.pack("%ds" % BLOCKSIZE, "".join(parts)) chksum = calc_chksums(buf[-BLOCKSIZE:])[0] buf = buf[:-364] + "%06o\0" % chksum + buf[-357:] return buf
Return a header block. info is a dictionary with file information, format must be one of the *_FORMAT constants.
_create_header
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def _create_payload(payload): """Return the string payload filled with zero bytes up to the next 512 byte border. """ blocks, remainder = divmod(len(payload), BLOCKSIZE) if remainder > 0: payload += (BLOCKSIZE - remainder) * NUL return payload
Return the string payload filled with zero bytes up to the next 512 byte border.
_create_payload
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def _create_pax_generic_header(cls, pax_headers, type=XHDTYPE): """Return a POSIX.1-2001 extended or global header sequence that contains a list of keyword, value pairs. The values must be unicode objects. """ records = [] for keyword, value in pax_headers.iteritems(): keyword = keyword.encode("utf8") value = value.encode("utf8") l = len(keyword) + len(value) + 3 # ' ' + '=' + '\n' n = p = 0 while True: n = l + len(str(p)) if n == p: break p = n records.append("%d %s=%s\n" % (p, keyword, value)) records = "".join(records) # We use a hardcoded "././@PaxHeader" name like star does # instead of the one that POSIX recommends. info = {} info["name"] = "././@PaxHeader" info["type"] = type info["size"] = len(records) info["magic"] = POSIX_MAGIC # Create pax header + record blocks. return cls._create_header(info, USTAR_FORMAT) + \ cls._create_payload(records)
Return a POSIX.1-2001 extended or global header sequence that contains a list of keyword, value pairs. The values must be unicode objects.
_create_pax_generic_header
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def frombuf(cls, buf): """Construct a TarInfo object from a 512 byte string buffer. """ if len(buf) == 0: raise EmptyHeaderError("empty header") if len(buf) != BLOCKSIZE: raise TruncatedHeaderError("truncated header") if buf.count(NUL) == BLOCKSIZE: raise EOFHeaderError("end of file header") chksum = nti(buf[148:156]) if chksum not in calc_chksums(buf): raise InvalidHeaderError("bad checksum") obj = cls() obj.buf = buf obj.name = nts(buf[0:100]) obj.mode = nti(buf[100:108]) obj.uid = nti(buf[108:116]) obj.gid = nti(buf[116:124]) obj.size = nti(buf[124:136]) obj.mtime = nti(buf[136:148]) obj.chksum = chksum obj.type = buf[156:157] obj.linkname = nts(buf[157:257]) obj.uname = nts(buf[265:297]) obj.gname = nts(buf[297:329]) obj.devmajor = nti(buf[329:337]) obj.devminor = nti(buf[337:345]) prefix = nts(buf[345:500]) # Old V7 tar format represents a directory as a regular # file with a trailing slash. if obj.type == AREGTYPE and obj.name.endswith("/"): obj.type = DIRTYPE # Remove redundant slashes from directories. if obj.isdir(): obj.name = obj.name.rstrip("/") # Reconstruct a ustar longname. if prefix and obj.type not in GNU_TYPES: obj.name = prefix + "/" + obj.name return obj
Construct a TarInfo object from a 512 byte string buffer.
frombuf
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def fromtarfile(cls, tarfile): """Return the next TarInfo object from TarFile object tarfile. """ buf = tarfile.fileobj.read(BLOCKSIZE) obj = cls.frombuf(buf) obj.offset = tarfile.fileobj.tell() - BLOCKSIZE return obj._proc_member(tarfile)
Return the next TarInfo object from TarFile object tarfile.
fromtarfile
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def _proc_member(self, tarfile): """Choose the right processing method depending on the type and call it. """ if self.type in (GNUTYPE_LONGNAME, GNUTYPE_LONGLINK): return self._proc_gnulong(tarfile) elif self.type == GNUTYPE_SPARSE: return self._proc_sparse(tarfile) elif self.type in (XHDTYPE, XGLTYPE, SOLARIS_XHDTYPE): return self._proc_pax(tarfile) else: return self._proc_builtin(tarfile)
Choose the right processing method depending on the type and call it.
_proc_member
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def _proc_builtin(self, tarfile): """Process a builtin type or an unknown type which will be treated as a regular file. """ self.offset_data = tarfile.fileobj.tell() offset = self.offset_data if self.isreg() or self.type not in SUPPORTED_TYPES: # Skip the following data blocks. offset += self._block(self.size) tarfile.offset = offset # Patch the TarInfo object with saved global # header information. self._apply_pax_info(tarfile.pax_headers, tarfile.encoding, tarfile.errors) return self
Process a builtin type or an unknown type which will be treated as a regular file.
_proc_builtin
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def _proc_gnulong(self, tarfile): """Process the blocks that hold a GNU longname or longlink member. """ buf = tarfile.fileobj.read(self._block(self.size)) # Fetch the next header and process it. try: next = self.fromtarfile(tarfile) except HeaderError: raise SubsequentHeaderError("missing or bad subsequent header") # Patch the TarInfo object from the next header with # the longname information. next.offset = self.offset if self.type == GNUTYPE_LONGNAME: next.name = nts(buf) elif self.type == GNUTYPE_LONGLINK: next.linkname = nts(buf) return next
Process the blocks that hold a GNU longname or longlink member.
_proc_gnulong
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def _proc_sparse(self, tarfile): """Process a GNU sparse header plus extra headers. """ buf = self.buf sp = _ringbuffer() pos = 386 lastpos = 0L realpos = 0L # There are 4 possible sparse structs in the # first header. for i in xrange(4): try: offset = nti(buf[pos:pos + 12]) numbytes = nti(buf[pos + 12:pos + 24]) except ValueError: break if offset > lastpos: sp.append(_hole(lastpos, offset - lastpos)) sp.append(_data(offset, numbytes, realpos)) realpos += numbytes lastpos = offset + numbytes pos += 24 isextended = ord(buf[482]) origsize = nti(buf[483:495]) # If the isextended flag is given, # there are extra headers to process. while isextended == 1: buf = tarfile.fileobj.read(BLOCKSIZE) pos = 0 for i in xrange(21): try: offset = nti(buf[pos:pos + 12]) numbytes = nti(buf[pos + 12:pos + 24]) except ValueError: break if offset > lastpos: sp.append(_hole(lastpos, offset - lastpos)) sp.append(_data(offset, numbytes, realpos)) realpos += numbytes lastpos = offset + numbytes pos += 24 isextended = ord(buf[504]) if lastpos < origsize: sp.append(_hole(lastpos, origsize - lastpos)) self.sparse = sp self.offset_data = tarfile.fileobj.tell() tarfile.offset = self.offset_data + self._block(self.size) self.size = origsize return self
Process a GNU sparse header plus extra headers.
_proc_sparse
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def _proc_pax(self, tarfile): """Process an extended or global header as described in POSIX.1-2001. """ # Read the header information. buf = tarfile.fileobj.read(self._block(self.size)) # A pax header stores supplemental information for either # the following file (extended) or all following files # (global). if self.type == XGLTYPE: pax_headers = tarfile.pax_headers else: pax_headers = tarfile.pax_headers.copy() # Parse pax header information. A record looks like that: # "%d %s=%s\n" % (length, keyword, value). length is the size # of the complete record including the length field itself and # the newline. keyword and value are both UTF-8 encoded strings. regex = re.compile(r"(\d+) ([^=]+)=", re.U) pos = 0 while True: match = regex.match(buf, pos) if not match: break length, keyword = match.groups() length = int(length) value = buf[match.end(2) + 1:match.start(1) + length - 1] keyword = keyword.decode("utf8") value = value.decode("utf8") pax_headers[keyword] = value pos += length # Fetch the next header. try: next = self.fromtarfile(tarfile) except HeaderError: raise SubsequentHeaderError("missing or bad subsequent header") if self.type in (XHDTYPE, SOLARIS_XHDTYPE): # Patch the TarInfo object with the extended header info. next._apply_pax_info(pax_headers, tarfile.encoding, tarfile.errors) next.offset = self.offset if "size" in pax_headers: # If the extended header replaces the size field, # we need to recalculate the offset where the next # header starts. offset = next.offset_data if next.isreg() or next.type not in SUPPORTED_TYPES: offset += next._block(next.size) tarfile.offset = offset return next
Process an extended or global header as described in POSIX.1-2001.
_proc_pax
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def _apply_pax_info(self, pax_headers, encoding, errors): """Replace fields with supplemental information from a previous pax extended or global header. """ for keyword, value in pax_headers.iteritems(): if keyword not in PAX_FIELDS: continue if keyword == "path": value = value.rstrip("/") if keyword in PAX_NUMBER_FIELDS: try: value = PAX_NUMBER_FIELDS[keyword](value) except ValueError: value = 0 else: value = uts(value, encoding, errors) setattr(self, keyword, value) self.pax_headers = pax_headers.copy()
Replace fields with supplemental information from a previous pax extended or global header.
_apply_pax_info
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def _block(self, count): """Round up a byte count by BLOCKSIZE and return it, e.g. _block(834) => 1024. """ blocks, remainder = divmod(count, BLOCKSIZE) if remainder: blocks += 1 return blocks * BLOCKSIZE
Round up a byte count by BLOCKSIZE and return it, e.g. _block(834) => 1024.
_block
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def __init__(self, name=None, mode="r", fileobj=None, format=None, tarinfo=None, dereference=None, ignore_zeros=None, encoding=None, errors=None, pax_headers=None, debug=None, errorlevel=None): """Open an (uncompressed) tar archive `name'. `mode' is either 'r' to read from an existing archive, 'a' to append data to an existing file or 'w' to create a new file overwriting an existing one. `mode' defaults to 'r'. If `fileobj' is given, it is used for reading or writing data. If it can be determined, `mode' is overridden by `fileobj's mode. `fileobj' is not closed, when TarFile is closed. """ modes = {"r": "rb", "a": "r+b", "w": "wb"} if mode not in modes: raise ValueError("mode must be 'r', 'a' or 'w'") self.mode = mode self._mode = modes[mode] if not fileobj: if self.mode == "a" and not os.path.exists(name): # Create nonexistent files in append mode. self.mode = "w" self._mode = "wb" fileobj = bltn_open(name, self._mode) self._extfileobj = False else: if name is None and hasattr(fileobj, "name"): name = fileobj.name if hasattr(fileobj, "mode"): self._mode = fileobj.mode self._extfileobj = True self.name = os.path.abspath(name) if name else None self.fileobj = fileobj # Init attributes. if format is not None: self.format = format if tarinfo is not None: self.tarinfo = tarinfo if dereference is not None: self.dereference = dereference if ignore_zeros is not None: self.ignore_zeros = ignore_zeros if encoding is not None: self.encoding = encoding if errors is not None: self.errors = errors elif mode == "r": self.errors = "utf-8" else: self.errors = "strict" if pax_headers is not None and self.format == PAX_FORMAT: self.pax_headers = pax_headers else: self.pax_headers = {} if debug is not None: self.debug = debug if errorlevel is not None: self.errorlevel = errorlevel # Init datastructures. self.closed = False self.members = [] # list of members as TarInfo objects self._loaded = False # flag if all members have been read self.offset = self.fileobj.tell() # current position in the archive file self.inodes = {} # dictionary caching the inodes of # archive members already added try: if self.mode == "r": self.firstmember = None self.firstmember = self.next() if self.mode == "a": # Move to the end of the archive, # before the first empty block. while True: self.fileobj.seek(self.offset) try: tarinfo = self.tarinfo.fromtarfile(self) self.members.append(tarinfo) except EOFHeaderError: self.fileobj.seek(self.offset) break except HeaderError, e: raise ReadError(str(e)) if self.mode in "aw": self._loaded = True if self.pax_headers: buf = self.tarinfo.create_pax_global_header(self.pax_headers.copy()) self.fileobj.write(buf) self.offset += len(buf) except: if not self._extfileobj: self.fileobj.close() self.closed = True raise
Open an (uncompressed) tar archive `name'. `mode' is either 'r' to read from an existing archive, 'a' to append data to an existing file or 'w' to create a new file overwriting an existing one. `mode' defaults to 'r'. If `fileobj' is given, it is used for reading or writing data. If it can be determined, `mode' is overridden by `fileobj's mode. `fileobj' is not closed, when TarFile is closed.
__init__
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def open(cls, name=None, mode="r", fileobj=None, bufsize=RECORDSIZE, **kwargs): """Open a tar archive for reading, writing or appending. Return an appropriate TarFile class. mode: 'r' or 'r:*' open for reading with transparent compression 'r:' open for reading exclusively uncompressed 'r:gz' open for reading with gzip compression 'r:bz2' open for reading with bzip2 compression 'a' or 'a:' open for appending, creating the file if necessary 'w' or 'w:' open for writing without compression 'w:gz' open for writing with gzip compression 'w:bz2' open for writing with bzip2 compression 'r|*' open a stream of tar blocks with transparent compression 'r|' open an uncompressed stream of tar blocks for reading 'r|gz' open a gzip compressed stream of tar blocks 'r|bz2' open a bzip2 compressed stream of tar blocks 'w|' open an uncompressed stream for writing 'w|gz' open a gzip compressed stream for writing 'w|bz2' open a bzip2 compressed stream for writing """ if not name and not fileobj: raise ValueError("nothing to open") if mode in ("r", "r:*"): # Find out which *open() is appropriate for opening the file. for comptype in cls.OPEN_METH: func = getattr(cls, cls.OPEN_METH[comptype]) if fileobj is not None: saved_pos = fileobj.tell() try: return func(name, "r", fileobj, **kwargs) except (ReadError, CompressionError), e: if fileobj is not None: fileobj.seek(saved_pos) continue raise ReadError("file could not be opened successfully") elif ":" in mode: filemode, comptype = mode.split(":", 1) filemode = filemode or "r" comptype = comptype or "tar" # Select the *open() function according to # given compression. if comptype in cls.OPEN_METH: func = getattr(cls, cls.OPEN_METH[comptype]) else: raise CompressionError("unknown compression type %r" % comptype) return func(name, filemode, fileobj, **kwargs) elif "|" in mode: filemode, comptype = mode.split("|", 1) filemode = filemode or "r" comptype = comptype or "tar" if filemode not in ("r", "w"): raise ValueError("mode must be 'r' or 'w'") stream = _Stream(name, filemode, comptype, fileobj, bufsize) try: t = cls(name, filemode, stream, **kwargs) except: stream.close() raise t._extfileobj = False return t elif mode in ("a", "w"): return cls.taropen(name, mode, fileobj, **kwargs) raise ValueError("undiscernible mode")
Open a tar archive for reading, writing or appending. Return an appropriate TarFile class. mode: 'r' or 'r:*' open for reading with transparent compression 'r:' open for reading exclusively uncompressed 'r:gz' open for reading with gzip compression 'r:bz2' open for reading with bzip2 compression 'a' or 'a:' open for appending, creating the file if necessary 'w' or 'w:' open for writing without compression 'w:gz' open for writing with gzip compression 'w:bz2' open for writing with bzip2 compression 'r|*' open a stream of tar blocks with transparent compression 'r|' open an uncompressed stream of tar blocks for reading 'r|gz' open a gzip compressed stream of tar blocks 'r|bz2' open a bzip2 compressed stream of tar blocks 'w|' open an uncompressed stream for writing 'w|gz' open a gzip compressed stream for writing 'w|bz2' open a bzip2 compressed stream for writing
open
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def taropen(cls, name, mode="r", fileobj=None, **kwargs): """Open uncompressed tar archive name for reading or writing. """ if mode not in ("r", "a", "w"): raise ValueError("mode must be 'r', 'a' or 'w'") return cls(name, mode, fileobj, **kwargs)
Open uncompressed tar archive name for reading or writing.
taropen
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def gzopen(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs): """Open gzip compressed tar archive name for reading or writing. Appending is not allowed. """ if mode not in ("r", "w"): raise ValueError("mode must be 'r' or 'w'") try: import gzip gzip.GzipFile except (ImportError, AttributeError): raise CompressionError("gzip module is not available") try: fileobj = gzip.GzipFile(name, mode, compresslevel, fileobj) except OSError: if fileobj is not None and mode == 'r': raise ReadError("not a gzip file") raise try: t = cls.taropen(name, mode, fileobj, **kwargs) except IOError: fileobj.close() if mode == 'r': raise ReadError("not a gzip file") raise except: fileobj.close() raise t._extfileobj = False return t
Open gzip compressed tar archive name for reading or writing. Appending is not allowed.
gzopen
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def bz2open(cls, name, mode="r", fileobj=None, compresslevel=9, **kwargs): """Open bzip2 compressed tar archive name for reading or writing. Appending is not allowed. """ if mode not in ("r", "w"): raise ValueError("mode must be 'r' or 'w'.") try: import bz2 except ImportError: raise CompressionError("bz2 module is not available") if fileobj is not None: fileobj = _BZ2Proxy(fileobj, mode) else: fileobj = bz2.BZ2File(name, mode, compresslevel=compresslevel) try: t = cls.taropen(name, mode, fileobj, **kwargs) except (IOError, EOFError): fileobj.close() if mode == 'r': raise ReadError("not a bzip2 file") raise except: fileobj.close() raise t._extfileobj = False return t
Open bzip2 compressed tar archive name for reading or writing. Appending is not allowed.
bz2open
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT
def close(self): """Close the TarFile. In write-mode, two finishing zero blocks are appended to the archive. """ if self.closed: return self.closed = True try: if self.mode in "aw": self.fileobj.write(NUL * (BLOCKSIZE * 2)) self.offset += (BLOCKSIZE * 2) # fill up the end with zero-blocks # (like option -b20 for tar does) blocks, remainder = divmod(self.offset, RECORDSIZE) if remainder > 0: self.fileobj.write(NUL * (RECORDSIZE - remainder)) finally: if not self._extfileobj: self.fileobj.close()
Close the TarFile. In write-mode, two finishing zero blocks are appended to the archive.
close
python
mchristopher/PokemonGo-DesktopMap
app/pywin/Lib/tarfile.py
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pywin/Lib/tarfile.py
MIT