desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Evaluate a marker. Return the boolean from evaluating the given marker against the environment. environment is an optional argument to override all or part of the determined environment. The environment is determined from the current Python process.'
def evaluate(self, environment=None):
current_environment = default_environment() if (environment is not None): current_environment.update(environment) return _evaluate_markers(self._markers, current_environment)
'Return the longhand version of the IP address as a string.'
@property def exploded(self):
return self._explode_shorthand_ip_string()
'Return the shorthand version of the IP address as a string.'
@property def compressed(self):
return _compat_str(self)
'The name of the reverse DNS pointer for the IP address, e.g.: >>> ipaddress.ip_address("127.0.0.1").reverse_pointer \'1.0.0.127.in-addr.arpa\' >>> ipaddress.ip_address("2001:db8::1").reverse_pointer \'1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa\''
@property def reverse_pointer(self):
return self._reverse_pointer()
'Turn the prefix length into a bitwise netmask Args: prefixlen: An integer, the prefix length. Returns: An integer.'
@classmethod def _ip_int_from_prefix(cls, prefixlen):
return (cls._ALL_ONES ^ (cls._ALL_ONES >> prefixlen))
'Return prefix length from the bitwise netmask. Args: ip_int: An integer, the netmask in expanded bitwise format Returns: An integer, the prefix length. Raises: ValueError: If the input intermingles zeroes & ones'
@classmethod def _prefix_from_ip_int(cls, ip_int):
trailing_zeroes = _count_righthand_zero_bits(ip_int, cls._max_prefixlen) prefixlen = (cls._max_prefixlen - trailing_zeroes) leading_ones = (ip_int >> trailing_zeroes) all_ones = ((1 << prefixlen) - 1) if (leading_ones != all_ones): byteslen = (cls._max_prefixlen // 8) details = _comp...
'Return prefix length from a numeric string Args: prefixlen_str: The string to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask'
@classmethod def _prefix_from_prefix_string(cls, prefixlen_str):
if (not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str)): cls._report_invalid_netmask(prefixlen_str) try: prefixlen = int(prefixlen_str) except ValueError: cls._report_invalid_netmask(prefixlen_str) if (not (0 <= prefixlen <= cls._max_prefixlen)): cls._report_invalid_ne...
'Turn a netmask/hostmask string into a prefix length Args: ip_str: The netmask/hostmask to be converted Returns: An integer, the prefix length. Raises: NetmaskValueError: If the input is not a valid netmask/hostmask'
@classmethod def _prefix_from_ip_string(cls, ip_str):
try: ip_int = cls._ip_int_from_string(ip_str) except AddressValueError: cls._report_invalid_netmask(ip_str) try: return cls._prefix_from_ip_int(ip_int) except ValueError: pass ip_int ^= cls._ALL_ONES try: return cls._prefix_from_ip_int(ip_int) except V...
'Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn\'t return the network or broadcast addresses.'
def hosts(self):
network = int(self.network_address) broadcast = int(self.broadcast_address) for x in _compat_range((network + 1), broadcast): (yield self._address_class(x))
'Tell if self is partly contained in other.'
def overlaps(self, other):
return ((self.network_address in other) or ((self.broadcast_address in other) or ((other.network_address in self) or (other.broadcast_address in self))))
'Number of hosts in the current subnet.'
@property def num_addresses(self):
return ((int(self.broadcast_address) - int(self.network_address)) + 1)
'Remove an address from a larger block. For example: addr1 = ip_network(\'192.0.2.0/28\') addr2 = ip_network(\'192.0.2.1/32\') addr1.address_exclude(addr2) = [IPv4Network(\'192.0.2.0/32\'), IPv4Network(\'192.0.2.2/31\'), IPv4Network(\'192.0.2.4/30\'), IPv4Network(\'192.0.2.8/29\')] or IPv6: addr1 = ip_network(\'2001:db...
def address_exclude(self, other):
if (not (self._version == other._version)): raise TypeError((u'%s and %s are not of the same version' % (self, other))) if (not isinstance(other, _BaseNetwork)): raise TypeError((u'%s is not a network object' % other)) if (not other.subnet_of(self)): ...
'Compare two IP objects. This is only concerned about the comparison of the integer representation of the network addresses. This means that the host bits aren\'t considered at all in this method. If you want to compare host bits, you can easily enough do a \'HostA._ip < HostB._ip\' Args: other: An IP object. Returns...
def compare_networks(self, other):
if (self._version != other._version): raise TypeError((u'%s and %s are not of the same type' % (self, other))) if (self.network_address < other.network_address): return (-1) if (self.network_address > other.network_address): return 1 if (self.netmask < oth...
'Network-only key function. Returns an object that identifies this address\' network and netmask. This function is a suitable "key" argument for sorted() and list.sort().'
def _get_networks_key(self):
return (self._version, self.network_address, self.netmask)
'The subnets which join to make the current subnet. In the case that self contains only one IP (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 for IPv6), yield an iterator with just ourself. Args: prefixlen_diff: An integer, the amount the prefix length should be increased by. This should not be set if new_pr...
def subnets(self, prefixlen_diff=1, new_prefix=None):
if (self._prefixlen == self._max_prefixlen): (yield self) return if (new_prefix is not None): if (new_prefix < self._prefixlen): raise ValueError(u'new prefix must be longer') if (prefixlen_diff != 1): raise ValueError(u'cannot set prefix...
'The supernet containing the current network. Args: prefixlen_diff: An integer, the amount the prefix length of the network should be decreased by. For example, given a /24 network and a prefixlen_diff of 3, a supernet with a /21 netmask is returned. Returns: An IPv4 network object. Raises: ValueError: If self.prefixl...
def supernet(self, prefixlen_diff=1, new_prefix=None):
if (self._prefixlen == 0): return self if (new_prefix is not None): if (new_prefix > self._prefixlen): raise ValueError(u'new prefix must be shorter') if (prefixlen_diff != 1): raise ValueError(u'cannot set prefixlen_diff and new_prefix') ...
'Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details.'
@property def is_multicast(self):
return (self.network_address.is_multicast and self.broadcast_address.is_multicast)
'Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges.'
@property def is_reserved(self):
return (self.network_address.is_reserved and self.broadcast_address.is_reserved)
'Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291.'
@property def is_link_local(self):
return (self.network_address.is_link_local and self.broadcast_address.is_link_local)
'Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv4-special-registry or iana-ipv6-special-registry.'
@property def is_private(self):
return (self.network_address.is_private and self.broadcast_address.is_private)
'Test if this address is allocated for public networks. Returns: A boolean, True if the address is not reserved per iana-ipv4-special-registry or iana-ipv6-special-registry.'
@property def is_global(self):
return (not self.is_private)
'Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2.'
@property def is_unspecified(self):
return (self.network_address.is_unspecified and self.broadcast_address.is_unspecified)
'Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3.'
@property def is_loopback(self):
return (self.network_address.is_loopback and self.broadcast_address.is_loopback)
'Make a (netmask, prefix_len) tuple from the given argument. Argument can be: - an integer (the prefix length) - a string representing the prefix length (e.g. "24") - a string representing the prefix netmask (e.g. "255.255.255.0")'
@classmethod def _make_netmask(cls, arg):
if (arg not in cls._netmask_cache): if isinstance(arg, _compat_int_types): prefixlen = arg else: try: prefixlen = cls._prefix_from_prefix_string(arg) except NetmaskValueError: prefixlen = cls._prefix_from_ip_string(arg) netm...
'Turn the given IP string into an integer for comparison. Args: ip_str: A string, the IP ip_str. Returns: The IP ip_str as an integer. Raises: AddressValueError: if ip_str isn\'t a valid IPv4 Address.'
@classmethod def _ip_int_from_string(cls, ip_str):
if (not ip_str): raise AddressValueError(u'Address cannot be empty') octets = ip_str.split(u'.') if (len(octets) != 4): raise AddressValueError((u'Expected 4 octets in %r' % ip_str)) try: return _compat_int_from_byte_vals(map(cls._parse_octet, octets), u'big'...
'Convert a decimal octet into an integer. Args: octet_str: A string, the number to parse. Returns: The octet as an integer. Raises: ValueError: if the octet isn\'t strictly a decimal from [0..255].'
@classmethod def _parse_octet(cls, octet_str):
if (not octet_str): raise ValueError(u'Empty octet not permitted') if (not cls._DECIMAL_DIGITS.issuperset(octet_str)): msg = u'Only decimal digits permitted in %r' raise ValueError((msg % octet_str)) if (len(octet_str) > 3): msg = u'At most 3 ...
'Turns a 32-bit integer into dotted decimal notation. Args: ip_int: An integer, the IP address. Returns: The IP address as a string in dotted decimal notation.'
@classmethod def _string_from_ip_int(cls, ip_int):
return u'.'.join((_compat_str((struct.unpack('!B', b)[0] if isinstance(b, bytes) else b)) for b in _compat_to_bytes(ip_int, 4, u'big')))
'Test if the IP string is a hostmask (rather than a netmask). Args: ip_str: A string, the potential hostmask. Returns: A boolean, True if the IP string is a hostmask.'
def _is_hostmask(self, ip_str):
bits = ip_str.split(u'.') try: parts = [x for x in map(int, bits) if (x in self._valid_mask_octets)] except ValueError: return False if (len(parts) != len(bits)): return False if (parts[0] < parts[(-1)]): return True return False
'Return the reverse DNS pointer name for the IPv4 address. This implements the method described in RFC1035 3.5.'
def _reverse_pointer(self):
reverse_octets = _compat_str(self).split(u'.')[::(-1)] return (u'.'.join(reverse_octets) + u'.in-addr.arpa')
'Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv4Address(\'192.0.2.1\') == IPv4Address(3221225985). or, more generally IPv4Address(int(IPv4Address(\'192.0.2.1\'))) == IPv4Address(\'192.0.2.1\') Raises: AddressValueError: If ipaddress isn\'t a valid IPv4 address.'
def __init__(self, address):
if isinstance(address, _compat_int_types): self._check_int_address(address) self._ip = address return if isinstance(address, bytes): self._check_packed_address(address, 4) bvs = _compat_bytes_to_byte_vals(address) self._ip = _compat_int_from_byte_vals(bvs, u'big')...
'The binary representation of this address.'
@property def packed(self):
return v4_int_to_packed(self._ip)
'Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within the reserved IPv4 Network range.'
@property def is_reserved(self):
return (self in self._constants._reserved_network)
'Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv4-special-registry.'
@property def is_private(self):
return any(((self in net) for net in self._constants._private_networks))
'Test if the address is reserved for multicast use. Returns: A boolean, True if the address is multicast. See RFC 3171 for details.'
@property def is_multicast(self):
return (self in self._constants._multicast_network)
'Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 5735 3.'
@property def is_unspecified(self):
return (self == self._constants._unspecified_address)
'Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback per RFC 3330.'
@property def is_loopback(self):
return (self in self._constants._loopback_network)
'Test if the address is reserved for link-local. Returns: A boolean, True if the address is link-local per RFC 3927.'
@property def is_link_local(self):
return (self in self._constants._linklocal_network)
'Instantiate a new IPv4 network object. Args: address: A string or integer representing the IP [& network]. \'192.0.2.0/24\' \'192.0.2.0/255.255.255.0\' \'192.0.0.2/0.0.0.255\' are all functionally the same in IPv4. Similarly, \'192.0.2.1\' \'192.0.2.1/255.255.255.255\' \'192.0.2.1/32\' are also functionally equivalent...
def __init__(self, address, strict=True):
_BaseNetwork.__init__(self, address) if isinstance(address, (_compat_int_types, bytes)): self.network_address = IPv4Address(address) (self.netmask, self._prefixlen) = self._make_netmask(self._max_prefixlen) return if isinstance(address, tuple): if (len(address) > 1): ...
'Test if this address is allocated for public networks. Returns: A boolean, True if the address is not reserved per iana-ipv4-special-registry.'
@property def is_global(self):
return ((not ((self.network_address in IPv4Network(u'100.64.0.0/10')) and (self.broadcast_address in IPv4Network(u'100.64.0.0/10')))) and (not self.is_private))
'Make a (netmask, prefix_len) tuple from the given argument. Argument can be: - an integer (the prefix length) - a string representing the prefix length (e.g. "24") - a string representing the prefix netmask (e.g. "255.255.255.0")'
@classmethod def _make_netmask(cls, arg):
if (arg not in cls._netmask_cache): if isinstance(arg, _compat_int_types): prefixlen = arg else: prefixlen = cls._prefix_from_prefix_string(arg) netmask = IPv6Address(cls._ip_int_from_prefix(prefixlen)) cls._netmask_cache[arg] = (netmask, prefixlen) return...
'Turn an IPv6 ip_str into an integer. Args: ip_str: A string, the IPv6 ip_str. Returns: An int, the IPv6 address Raises: AddressValueError: if ip_str isn\'t a valid IPv6 Address.'
@classmethod def _ip_int_from_string(cls, ip_str):
if (not ip_str): raise AddressValueError(u'Address cannot be empty') parts = ip_str.split(u':') _min_parts = 3 if (len(parts) < _min_parts): msg = (u'At least %d parts expected in %r' % (_min_parts, ip_str)) raise AddressValueError(msg) if (u'.' in ...
'Convert an IPv6 hextet string into an integer. Args: hextet_str: A string, the number to parse. Returns: The hextet as an integer. Raises: ValueError: if the input isn\'t strictly a hex number from [0..FFFF].'
@classmethod def _parse_hextet(cls, hextet_str):
if (not cls._HEX_DIGITS.issuperset(hextet_str)): raise ValueError((u'Only hex digits permitted in %r' % hextet_str)) if (len(hextet_str) > 4): msg = u'At most 4 characters permitted in %r' raise ValueError((msg % hextet_str)) return int(hextet_str, 16...
'Compresses a list of hextets. Compresses a list of strings, replacing the longest continuous sequence of "0" in the list with "" and adding empty strings at the beginning or at the end of the string such that subsequently calling ":".join(hextets) will produce the compressed version of the IPv6 address. Args: hextets:...
@classmethod def _compress_hextets(cls, hextets):
best_doublecolon_start = (-1) best_doublecolon_len = 0 doublecolon_start = (-1) doublecolon_len = 0 for (index, hextet) in enumerate(hextets): if (hextet == u'0'): doublecolon_len += 1 if (doublecolon_start == (-1)): doublecolon_start = index ...
'Turns a 128-bit integer into hexadecimal notation. Args: ip_int: An integer, the IP address. Returns: A string, the hexadecimal representation of the address. Raises: ValueError: The address is bigger than 128 bits of all ones.'
@classmethod def _string_from_ip_int(cls, ip_int=None):
if (ip_int is None): ip_int = int(cls._ip) if (ip_int > cls._ALL_ONES): raise ValueError(u'IPv6 address is too large') hex_str = (u'%032x' % ip_int) hextets = [(u'%x' % int(hex_str[x:(x + 4)], 16)) for x in range(0, 32, 4)] hextets = cls._compress_hextets(hextets) ret...
'Expand a shortened IPv6 address. Args: ip_str: A string, the IPv6 address. Returns: A string, the expanded IPv6 address.'
def _explode_shorthand_ip_string(self):
if isinstance(self, IPv6Network): ip_str = _compat_str(self.network_address) elif isinstance(self, IPv6Interface): ip_str = _compat_str(self.ip) else: ip_str = _compat_str(self) ip_int = self._ip_int_from_string(ip_str) hex_str = (u'%032x' % ip_int) parts = [hex_str[x:(x ...
'Return the reverse DNS pointer name for the IPv6 address. This implements the method described in RFC3596 2.5.'
def _reverse_pointer(self):
reverse_chars = self.exploded[::(-1)].replace(u':', u'') return (u'.'.join(reverse_chars) + u'.ip6.arpa')
'Instantiate a new IPv6 address object. Args: address: A string or integer representing the IP Additionally, an integer can be passed, so IPv6Address(\'2001:db8::\') == IPv6Address(42540766411282592856903984951653826560) or, more generally IPv6Address(int(IPv6Address(\'2001:db8::\'))) == IPv6Address(\'2001:db8::\') Rai...
def __init__(self, address):
if isinstance(address, _compat_int_types): self._check_int_address(address) self._ip = address return if isinstance(address, bytes): self._check_packed_address(address, 16) bvs = _compat_bytes_to_byte_vals(address) self._ip = _compat_int_from_byte_vals(bvs, u'big'...
'The binary representation of this address.'
@property def packed(self):
return v6_int_to_packed(self._ip)
'Test if the address is reserved for multicast use. Returns: A boolean, True if the address is a multicast address. See RFC 2373 2.7 for details.'
@property def is_multicast(self):
return (self in self._constants._multicast_network)
'Test if the address is otherwise IETF reserved. Returns: A boolean, True if the address is within one of the reserved IPv6 Network ranges.'
@property def is_reserved(self):
return any(((self in x) for x in self._constants._reserved_networks))
'Test if the address is reserved for link-local. Returns: A boolean, True if the address is reserved per RFC 4291.'
@property def is_link_local(self):
return (self in self._constants._linklocal_network)
'Test if the address is reserved for site-local. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193. Returns: A boolean, True if the address is reserved per RFC 3513 2.5.6.'
@property def is_site_local(self):
return (self in self._constants._sitelocal_network)
'Test if this address is allocated for private networks. Returns: A boolean, True if the address is reserved per iana-ipv6-special-registry.'
@property def is_private(self):
return any(((self in net) for net in self._constants._private_networks))
'Test if this address is allocated for public networks. Returns: A boolean, true if the address is not reserved per iana-ipv6-special-registry.'
@property def is_global(self):
return (not self.is_private)
'Test if the address is unspecified. Returns: A boolean, True if this is the unspecified address as defined in RFC 2373 2.5.2.'
@property def is_unspecified(self):
return (self._ip == 0)
'Test if the address is a loopback address. Returns: A boolean, True if the address is a loopback address as defined in RFC 2373 2.5.3.'
@property def is_loopback(self):
return (self._ip == 1)
'Return the IPv4 mapped address. Returns: If the IPv6 address is a v4 mapped address, return the IPv4 mapped address. Return None otherwise.'
@property def ipv4_mapped(self):
if ((self._ip >> 32) != 65535): return None return IPv4Address((self._ip & 4294967295))
'Tuple of embedded teredo IPs. Returns: Tuple of the (server, client) IPs or None if the address doesn\'t appear to be a teredo address (doesn\'t start with 2001::/32)'
@property def teredo(self):
if ((self._ip >> 96) != 536936448): return None return (IPv4Address(((self._ip >> 64) & 4294967295)), IPv4Address(((~ self._ip) & 4294967295)))
'Return the IPv4 6to4 embedded address. Returns: The IPv4 6to4-embedded address if present or None if the address doesn\'t appear to contain a 6to4 embedded address.'
@property def sixtofour(self):
if ((self._ip >> 112) != 8194): return None return IPv4Address(((self._ip >> 80) & 4294967295))
'Instantiate a new IPv6 Network object. Args: address: A string or integer representing the IPv6 network or the IP and prefix/netmask. \'2001:db8::/128\' \'2001:db8:0000:0000:0000:0000:0000:0000/128\' \'2001:db8::\' are all functionally the same in IPv6. That is to say, failing to provide a subnetmask will create an o...
def __init__(self, address, strict=True):
_BaseNetwork.__init__(self, address) if isinstance(address, (bytes, _compat_int_types)): self.network_address = IPv6Address(address) (self.netmask, self._prefixlen) = self._make_netmask(self._max_prefixlen) return if isinstance(address, tuple): if (len(address) > 1): ...
'Generate Iterator over usable hosts in a network. This is like __iter__ except it doesn\'t return the Subnet-Router anycast address.'
def hosts(self):
network = int(self.network_address) broadcast = int(self.broadcast_address) for x in _compat_range((network + 1), (broadcast + 1)): (yield self._address_class(x))
'Test if the address is reserved for site-local. Note that the site-local address space has been deprecated by RFC 3879. Use is_private to test if this address is in the space of unique local addresses as defined by RFC 4193. Returns: A boolean, True if the address is reserved per RFC 3513 2.5.6.'
@property def is_site_local(self):
return (self.network_address.is_site_local and self.broadcast_address.is_site_local)
'Acquire the lock. * If timeout is omitted (or None), wait forever trying to lock the file. * If timeout > 0, try to acquire the lock for that many seconds. If the lock period expires and the file is still locked, raise LockTimeout. * If timeout <= 0, raise AlreadyLocked immediately if the file is already locked.'
def acquire(self, timeout=None):
raise NotImplemented('implement in subclass')
'Release the lock. If the file is not locked, raise NotLocked.'
def release(self):
raise NotImplemented('implement in subclass')
'Context manager support.'
def __enter__(self):
self.acquire() return self
'Context manager support.'
def __exit__(self, *_exc):
self.release()
'>>> lock = LockBase(\'somefile\') >>> lock = LockBase(\'somefile\', threaded=False)'
def __init__(self, path, threaded=True, timeout=None):
super(LockBase, self).__init__(path) self.lock_file = (os.path.abspath(path) + '.lock') self.hostname = socket.gethostname() self.pid = os.getpid() if threaded: t = threading.current_thread() ident = getattr(t, 'ident', hash(t)) self.tname = ('-%x' % (ident & 4294967295)) ...
'Tell whether or not the file is locked.'
def is_locked(self):
raise NotImplemented('implement in subclass')
'Return True if this object is locking the file.'
def i_am_locking(self):
raise NotImplemented('implement in subclass')
'Remove a lock. Useful if a locking thread failed to unlock.'
def break_lock(self):
raise NotImplemented('implement in subclass')
'Get the PID from the lock file.'
def read_pid(self):
return read_pid_from_pidfile(self.path)
'Test if the lock is currently held. The lock is held if the PID file for this lock exists.'
def is_locked(self):
return os.path.exists(self.path)
'Test if the lock is held by the current process. Returns ``True`` if the current process ID matches the number stored in the PID file.'
def i_am_locking(self):
return (self.is_locked() and (os.getpid() == self.read_pid()))
'Acquire the lock. Creates the PID file for this lock, or raises an error if the lock could not be acquired.'
def acquire(self, timeout=None):
timeout = (timeout if (timeout is not None) else self.timeout) end_time = time.time() if ((timeout is not None) and (timeout > 0)): end_time += timeout while True: try: write_pid_to_pidfile(self.path) except OSError as exc: if (exc.errno == errno.EEXIST): ...
'Release the lock. Removes the PID file to release the lock, or raises an error if the current process does not hold the lock.'
def release(self):
if (not self.is_locked()): raise NotLocked(('%s is not locked' % self.path)) if (not self.i_am_locking()): raise NotMyLock(('%s is locked, but not by me' % self.path)) remove_existing_pidfile(self.path)
'Break an existing lock. Removes the PID file if it already exists, otherwise does nothing.'
def break_lock(self):
remove_existing_pidfile(self.path)
'>>> lock = MkdirLockFile(\'somefile\') >>> lock = MkdirLockFile(\'somefile\', threaded=False)'
def __init__(self, path, threaded=True, timeout=None):
LockBase.__init__(self, path, threaded, timeout) self.unique_name = os.path.join(self.lock_file, ('%s.%s%s' % (self.hostname, self.tname, self.pid)))
'>>> lock = SQLiteLockFile(\'somefile\') >>> lock = SQLiteLockFile(\'somefile\', threaded=False)'
def __init__(self, path, threaded=True, timeout=None):
LockBase.__init__(self, path, threaded, timeout) self.lock_file = unicode(self.lock_file) self.unique_name = unicode(self.unique_name) if (SQLiteLockFile.testdb is None): import tempfile (_fd, testdb) = tempfile.mkstemp() os.close(_fd) os.unlink(testdb) del _fd, t...
'supported attributes by name are: - lineno - returns the line number of the exception text - col - returns the column number of the exception text - line - returns the line containing the exception text'
def __getattr__(self, aname):
if (aname == 'lineno'): return lineno(self.loc, self.pstr) elif (aname in ('col', 'column')): return col(self.loc, self.pstr) elif (aname == 'line'): return line(self.loc, self.pstr) else: raise AttributeError(aname)
'Extracts the exception line from the input string, and marks the location of the exception with a special symbol.'
def markInputline(self, markerString='>!<'):
line_str = self.line line_column = (self.column - 1) if markerString: line_str = ''.join((line_str[:line_column], markerString, line_str[line_column:])) return line_str.strip()
'Returns all named result keys.'
def iterkeys(self):
if hasattr(self.__tokdict, 'iterkeys'): return self.__tokdict.iterkeys() else: return iter(self.__tokdict)
'Returns all named result values.'
def itervalues(self):
return (self[k] for k in self.iterkeys())
'Since keys() returns an iterator, this method is helpful in bypassing code that looks for the existence of any defined results names.'
def haskeys(self):
return bool(self.__tokdict)
'Removes and returns item at specified index (default=last). Supports both list and dict semantics for pop(). If passed no argument or an integer argument, it will use list semantics and pop tokens from the list of parsed tokens. If passed a non-integer argument (most likely a string), it will use dict semantics and po...
def pop(self, *args, **kwargs):
if (not args): args = [(-1)] for (k, v) in kwargs.items(): if (k == 'default'): args = (args[0], v) else: raise TypeError(("pop() got an unexpected keyword argument '%s'" % k)) if (isinstance(args[0], int) or (len(args) == 1) or (args[0] in s...
'Returns named result matching the given key, or if there is no such name, then returns the given C{defaultValue} or C{None} if no C{defaultValue} is specified.'
def get(self, key, defaultValue=None):
if (key in self): return self[key] else: return defaultValue
'Inserts new element at location index in the list of parsed tokens.'
def insert(self, index, insStr):
self.__toklist.insert(index, insStr) for (name, occurrences) in self.__tokdict.items(): for (k, (value, position)) in enumerate(occurrences): occurrences[k] = _ParseResultsWithOffset(value, (position + (position > index)))
'Add single element to end of ParseResults list of elements.'
def append(self, item):
self.__toklist.append(item)
'Add sequence of elements to end of ParseResults list of elements.'
def extend(self, itemseq):
if isinstance(itemseq, ParseResults): self += itemseq else: self.__toklist.extend(itemseq)
'Clear all elements and results names.'
def clear(self):
del self.__toklist[:] self.__tokdict.clear()
'Returns the parse results as a nested list of matching tokens, all converted to strings.'
def asList(self):
return [(res.asList() if isinstance(res, ParseResults) else res) for res in self.__toklist]
'Returns the named parse results as a nested dictionary.'
def asDict(self):
if PY_3: item_fn = self.items else: item_fn = self.iteritems return dict((((k, v.asDict()) if isinstance(v, ParseResults) else (k, v)) for (k, v) in item_fn()))
'Returns a new copy of a C{ParseResults} object.'
def copy(self):
ret = ParseResults(self.__toklist) ret.__tokdict = self.__tokdict.copy() ret.__parent = self.__parent ret.__accumNames.update(self.__accumNames) ret.__name = self.__name return ret
'Returns the parse results as XML. Tags are created for tokens and lists that have defined results names.'
def asXML(self, doctag=None, namedItemsOnly=False, indent='', formatted=True):
nl = '\n' out = [] namedItems = dict(((v[1], k) for (k, vlist) in self.__tokdict.items() for v in vlist)) nextLevelIndent = (indent + ' ') if (not formatted): indent = '' nextLevelIndent = '' nl = '' selfTag = None if (doctag is not None): selfTag = doc...
'Returns the results name for this token expression.'
def getName(self):
if self.__name: return self.__name elif self.__parent: par = self.__parent() if par: return par.__lookup(self) else: return None elif ((len(self) == 1) and (len(self.__tokdict) == 1) and (self.__tokdict.values()[0][0][1] in (0, (-1)))): return ...
'Diagnostic method for listing out the contents of a C{ParseResults}. Accepts an optional C{indent} argument so that this string can be embedded in a nested display of other data.'
def dump(self, indent='', depth=0):
out = [] NL = '\n' out.append((indent + _ustr(self.asList()))) if self.haskeys(): items = sorted(self.items()) for (k, v) in items: if out: out.append(NL) out.append(('%s%s- %s: ' % (indent, (' ' * depth), k))) if isinstanc...
'Pretty-printer for parsed results as a list, using the C{pprint} module. Accepts additional positional or keyword args as defined for the C{pprint.pprint} method. (U{http://docs.python.org/3/library/pprint.html#pprint.pprint})'
def pprint(self, *args, **kwargs):
pprint.pprint(self.asList(), *args, **kwargs)
'Overrides the default whitespace chars'
@staticmethod def setDefaultWhitespaceChars(chars):
ParserElement.DEFAULT_WHITE_CHARS = chars
'Set class to be used for inclusion of string literals into a parser.'
@staticmethod def inlineLiteralsUsing(cls):
ParserElement.literalStringClass = cls
'Make a copy of this C{ParserElement}. Useful for defining different parse actions for the same parsing pattern, using copies of the original parse element.'
def copy(self):
cpy = copy.copy(self) cpy.parseAction = self.parseAction[:] cpy.ignoreExprs = self.ignoreExprs[:] if self.copyDefaultWhiteChars: cpy.whiteChars = ParserElement.DEFAULT_WHITE_CHARS return cpy
'Define name for this expression, for use in debugging.'
def setName(self, name):
self.name = name self.errmsg = ('Expected ' + self.name) if hasattr(self, 'exception'): self.exception.msg = self.errmsg return self