Current File : /home/mmdealscpanel/yummmdeals.com/pyudev.tar
__init__.py000064400000004676150351420040006664 0ustar00# -*- coding: utf-8 -*-
# Copyright (C) 2010, 2011, 2012 Sebastian Wiesner <lunaryorn@gmail.com>

# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.

# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
# for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA


"""
    pyudev
    ======

    A binding to libudev.

    The :class:`Context` provides the connection to the udev device database
    and enumerates devices.  Individual devices are represented by the
    :class:`Device` class.

    Device monitoring is provided by :class:`Monitor` and
    :class:`MonitorObserver`.  With :mod:`pyudev.pyqt4`, :mod:`pyudev.pyside`,
    :mod:`pyudev.glib` and :mod:`pyudev.wx` device monitoring can be integrated
    into the event loop of various GUI toolkits.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals


from pyudev.device import Attributes
from pyudev.device import Device
from pyudev.device import Devices
from pyudev.device import DeviceNotFoundAtPathError
from pyudev.device import DeviceNotFoundByFileError
from pyudev.device import DeviceNotFoundByNameError
from pyudev.device import DeviceNotFoundByNumberError
from pyudev.device import DeviceNotFoundError
from pyudev.device import DeviceNotFoundInEnvironmentError
from pyudev.device import Tags

from pyudev.discover import DeviceFileHypothesis
from pyudev.discover import DeviceNameHypothesis
from pyudev.discover import DeviceNumberHypothesis
from pyudev.discover import DevicePathHypothesis
from pyudev.discover import Discovery

from pyudev.core import Context
from pyudev.core import Enumerator

from pyudev.monitor import Monitor
from pyudev.monitor import MonitorObserver

from pyudev.version import __version__
from pyudev.version import __version_info__

from pyudev._util import udev_version
discover.py000064400000026364150351420040006741 0ustar00# -*- coding: utf-8 -*-
# Copyright (C) 2015 mulhern <amulhern@redhat.com>

# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.

# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
# for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA


"""
    pyudev.discover
    ===============

    Tools to discover a device given limited information.

    .. moduleauthor::  mulhern <amulhern@redhat.com>
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import abc
import functools
import os
import re
import six

from pyudev.device import Devices
from pyudev.device import DeviceNotFoundError


def wrap_exception(func):
    """
    Allow Device discovery methods to return None instead of raising an
    exception.
    """

    @functools.wraps(func)
    def the_func(*args, **kwargs):
        """
        Returns result of calling ``func`` on ``args``, ``kwargs``.
        Returns None if ``func`` raises :exc:`DeviceNotFoundError`.
        """
        try:
            return func(*args, **kwargs)
        except DeviceNotFoundError:
            return None

    return the_func

@six.add_metaclass(abc.ABCMeta)
class Hypothesis(object):
    """
    Represents a hypothesis about the meaning of the device identifier.
    """

    @classmethod
    @abc.abstractmethod
    def match(cls, value): # pragma: no cover
        """
        Match the given string according to the hypothesis.

        The purpose of this method is to obtain a value corresponding to
        ``value`` if that is possible. It may use a regular expression, but
        in general it should just return ``value`` and let the lookup method
        sort out the rest.

        :param str value: the string to inspect
        :returns: the matched thing or None if unmatched
        :rtype: the type of lookup's key parameter or NoneType
        """
        raise NotImplementedError()

    @classmethod
    @abc.abstractmethod
    def lookup(cls, context, key): # pragma: no cover
        """
        Lookup the given string according to the hypothesis.

        :param Context context: the pyudev context
        :param key: a key with which to lookup the device
        :type key: the type of match's return value if not None
        :returns: a list of Devices obtained
        :rtype: frozenset of :class:`Device`
        """
        raise NotImplementedError()

    @classmethod
    def setup(cls, context):
        """
        A potentially expensive method that may allow an :class:`Hypothesis`
        to find devices more rapidly or to find a device that it would
        otherwise miss.

        :param Context context: the pyudev context
        """
        pass

    @classmethod
    def get_devices(cls, context, value):
        """
        Get any devices that may correspond to the given string.

        :param Context context: the pyudev context
        :param str value: the value to look for
        :returns: a list of devices obtained
        :rtype: set of :class:`Device`
        """
        key = cls.match(value)
        return cls.lookup(context, key) if key is not None else frozenset()


class DeviceNumberHypothesis(Hypothesis):
    """
    Represents the hypothesis that the device is a device number.

    The device may be separated into major/minor number or a composite number.
    """

    @classmethod
    def _match_major_minor(cls, value):
        """
        Match the number under the assumption that it is a major,minor pair.

        :param str value: value to match
        :returns: the device number or None
        :rtype: int or NoneType
        """
        major_minor_re = re.compile(
           r'^(?P<major>\d+)(\D+)(?P<minor>\d+)$'
        )
        match = major_minor_re.match(value)
        return match and os.makedev(
           int(match.group('major')),
           int(match.group('minor'))
        )

    @classmethod
    def _match_number(cls, value):
        """
        Match the number under the assumption that it is a single number.

        :param str value: value to match
        :returns: the device number or None
        :rtype: int or NoneType
        """
        number_re = re.compile(r'^(?P<number>\d+)$')
        match = number_re.match(value)
        return match and int(match.group('number'))

    @classmethod
    def match(cls, value):
        """
        Match the number under the assumption that it is a device number.

        :returns: the device number or None
        :rtype: int or NoneType
        """
        return cls._match_major_minor(value) or cls._match_number(value)

    @classmethod
    def find_subsystems(cls, context):
        """
        Find subsystems in /sys/dev.

        :param Context context: the context
        :returns: a lis of available subsystems
        :rtype: list of str
        """
        sys_path = context.sys_path
        return os.listdir(os.path.join(sys_path, 'dev'))

    @classmethod
    def lookup(cls, context, key):
        """
        Lookup by the device number.

        :param Context context: the context
        :param int key: the device number
        :returns: a list of matching devices
        :rtype: frozenset of :class:`Device`
        """
        func = wrap_exception(Devices.from_device_number)
        res = (func(context, s, key) for s in cls.find_subsystems(context))
        return frozenset(r for r in res if r is not None)


class DevicePathHypothesis(Hypothesis):
    """
    Discover the device assuming the identifier is a device path.
    """

    @classmethod
    def match(cls, value):
        """
        Match ``value`` under the assumption that it is a device path.

        :returns: the device path or None
        :rtype: str or NoneType
        """
        return value

    @classmethod
    def lookup(cls, context, key):
        """
        Lookup by the path.

        :param Context context: the context
        :param str key: the device path
        :returns: a list of matching devices
        :rtype: frozenset of :class:`Device`
        """
        res = wrap_exception(Devices.from_path)(context, key)
        return frozenset((res,)) if res is not None else frozenset()


class DeviceNameHypothesis(Hypothesis):
    """
    Discover the device assuming the input is a device name.

    Try every available subsystem.
    """

    @classmethod
    def find_subsystems(cls, context):
        """
        Find all subsystems in sysfs.

        :param Context context: the context
        :rtype: frozenset
        :returns: subsystems in sysfs
        """
        sys_path = context.sys_path
        dirnames = ('bus', 'class', 'subsystem')
        absnames = (os.path.join(sys_path, name) for name in dirnames)
        realnames = (d for d in absnames if os.path.isdir(d))
        return frozenset(n for d in realnames for n in os.listdir(d))

    @classmethod
    def match(cls, value):
        """
        Match ``value`` under the assumption that it is a device name.

        :returns: the device path or None
        :rtype: str or NoneType
        """
        return value

    @classmethod
    def lookup(cls, context, key):
        """
        Lookup by the path.

        :param Context context: the context
        :param str key: the device path
        :returns: a list of matching devices
        :rtype: frozenset of :class:`Device`
        """
        func = wrap_exception(Devices.from_name)
        res = (func(context, s, key) for s in cls.find_subsystems(context))
        return frozenset(r for r in res if r is not None)


class DeviceFileHypothesis(Hypothesis):
    """
    Discover the device assuming the value is some portion of a device file.

    The device file may be a link to a device node.
    """

    _LINK_DIRS = [
       '/dev',
       '/dev/disk/by-id',
       '/dev/disk/by-label',
       '/dev/disk/by-partlabel',
       '/dev/disk/by-partuuid',
       '/dev/disk/by-path',
       '/dev/disk/by-uuid',
       '/dev/input/by-path',
       '/dev/mapper',
       '/dev/md',
       '/dev/vg'
    ]

    @classmethod
    def get_link_dirs(cls, context):
        """
        Get all directories that may contain links to device nodes.

        This method checks the device links of every device, so it is very
        expensive.

        :param Context context: the context
        :returns: a sorted list of directories that contain device links
        :rtype: list
        """
        devices = context.list_devices()
        devices_with_links = (d for d in devices if list(d.device_links))
        links = (l for d in devices_with_links for l in d.device_links)
        return sorted(set(os.path.dirname(l) for l in links))

    @classmethod
    def setup(cls, context):
        """
        Set the link directories to be used when discovering by file.

        Uses `get_link_dirs`, so is as expensive as it is.

        :param Context context: the context
        """
        cls._LINK_DIRS = cls.get_link_dirs(context)

    @classmethod
    def match(cls, value):
        return value

    @classmethod
    def lookup(cls, context, key):
        """
        Lookup the device under the assumption that the key is part of
        the name of a device file.

        :param Context context: the context
        :param str key: a portion of the device file name

        It is assumed that either it is the whole name of the device file
        or it is the basename.

        A device file may be a device node or a device link.
        """
        func = wrap_exception(Devices.from_device_file)
        if '/' in key:
            device = func(context, key)
            return frozenset((device,)) if device is not None else frozenset()
        else:
            files = (os.path.join(ld, key) for ld in cls._LINK_DIRS)
            devices = (func(context, f) for f in files)
            return frozenset(d for d in devices if d is not None)


class Discovery(object):
    # pylint: disable=too-few-public-methods
    """
    Provides discovery methods for devices.
    """

    _HYPOTHESES = [
       DeviceFileHypothesis,
       DeviceNameHypothesis,
       DeviceNumberHypothesis,
       DevicePathHypothesis
    ]

    def __init__(self):
        self._hypotheses = self._HYPOTHESES

    def setup(self, context):
        """
        Set up individual hypotheses.

        May be an expensive call.

        :param Context context: the context
        """
        for hyp in self._hypotheses:
            hyp.setup(context)

    def get_devices(self, context, value):
        """
        Get the devices corresponding to value.

        :param Context context: the context
        :param str value: some identifier of the device
        :returns: a list of corresponding devices
        :rtype: frozenset of :class:`Device`
        """
        return frozenset(
           d for h in self._hypotheses for d in h.get_devices(context, value)
        )
_util.py000064400000015450150351420040006231 0ustar00# -*- coding: utf-8 -*-
# Copyright (C) 2010, 2011, 2012 Sebastian Wiesner <lunaryorn@gmail.com>

# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.

# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
# for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA


"""
    pyudev._util
    ============

    Internal utilities

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
"""


from __future__ import (print_function, division, unicode_literals,
                        absolute_import)

try:
    from subprocess import check_output
except ImportError:
    from pyudev._compat import check_output

import os
import sys
import stat
import errno

import six


def ensure_byte_string(value):
    """
    Return the given ``value`` as bytestring.

    If the given ``value`` is not a byte string, but a real unicode string, it
    is encoded with the filesystem encoding (as in
    :func:`sys.getfilesystemencoding()`).
    """
    if not isinstance(value, bytes):
        value = value.encode(sys.getfilesystemencoding())
    return value


def ensure_unicode_string(value):
    """
    Return the given ``value`` as unicode string.

    If the given ``value`` is not a unicode string, but a byte string, it is
    decoded with the filesystem encoding (as in
    :func:`sys.getfilesystemencoding()`).
    """
    if not isinstance(value, six.text_type):
        value = value.decode(sys.getfilesystemencoding())
    return value


def property_value_to_bytes(value):
    """
    Return a byte string, which represents the given ``value`` in a way
    suitable as raw value of an udev property.

    If ``value`` is a boolean object, it is converted to ``'1'`` or ``'0'``,
    depending on whether ``value`` is ``True`` or ``False``.  If ``value`` is a
    byte string already, it is returned unchanged.  Anything else is simply
    converted to a unicode string, and then passed to
    :func:`ensure_byte_string`.
    """
    # udev represents boolean values as 1 or 0, therefore an explicit
    # conversion to int is required for boolean values
    if isinstance(value, bool):
        value = int(value)
    if isinstance(value, bytes):
        return value
    else:
        return ensure_byte_string(six.text_type(value))


def string_to_bool(value):
    """
    Convert the given unicode string ``value`` to a boolean object.

    If ``value`` is ``'1'``, ``True`` is returned.  If ``value`` is ``'0'``,
    ``False`` is returned.  Any other value raises a
    :exc:`~exceptions.ValueError`.
    """
    if value not in ('1', '0'):
        raise ValueError('Not a boolean value: {0!r}'.format(value))
    return value == '1'


def udev_list_iterate(libudev, entry):
    """
    Iteration helper for udev list entry objects.

    Yield a tuple ``(name, value)``.  ``name`` and ``value`` are bytestrings
    containing the name and the value of the list entry.  The exact contents
    depend on the list iterated over.
    """
    while entry:
        name = libudev.udev_list_entry_get_name(entry)
        value = libudev.udev_list_entry_get_value(entry)
        yield (name, value)
        entry = libudev.udev_list_entry_get_next(entry)


def get_device_type(filename):
    """
    Get the device type of a device file.

    ``filename`` is a string containing the path of a device file.

    Return ``'char'`` if ``filename`` is a character device, or ``'block'`` if
    ``filename`` is a block device.  Raise :exc:`~exceptions.ValueError` if
    ``filename`` is no device file at all.  Raise
    :exc:`~exceptions.EnvironmentError` if ``filename`` does not exist or if
    its metadata was inaccessible.

    .. versionadded:: 0.15
    """
    mode = os.stat(filename).st_mode
    if stat.S_ISCHR(mode):
        return 'char'
    elif stat.S_ISBLK(mode):
        return 'block'
    else:
        raise ValueError('not a device file: {0!r}'.format(filename))


def eintr_retry_call(func, *args, **kwargs):
    """
    Handle interruptions to an interruptible system call.

    Run an interruptible system call in a loop and retry if it raises EINTR.
    The signal calls that may raise EINTR prior to Python 3.5 are listed in
    PEP 0475.  Any calls to these functions must be wrapped in eintr_retry_call
    in order to handle EINTR returns in older versions of Python.

    This function is safe to use under Python 3.5 and newer since the wrapped
    function will simply return without raising EINTR.

    This function is based on _eintr_retry_call in python's subprocess.py.
    """

    # select.error inherits from Exception instead of OSError in Python 2
    import select

    while True:
        try:
            return func(*args, **kwargs)
        except (OSError, IOError, select.error) as err:
            # If this is not an IOError or OSError, it's the old select.error
            # type, which means that the errno is only accessible via subscript
            if isinstance(err, (OSError, IOError)):
                error_code = err.errno
            else:
                error_code = err.args[0]

            if error_code == errno.EINTR:
                continue
            raise

def udev_version():
    """
    Get the version of the underlying udev library.

    udev doesn't use a standard major-minor versioning scheme, but instead
    labels releases with a single consecutive number.  Consequently, the
    version number returned by this function is a single integer, and not a
    tuple (like for instance the interpreter version in
    :data:`sys.version_info`).

    As libudev itself does not provide a function to query the version number,
    this function calls the ``udevadm`` utility, so be prepared to catch
    :exc:`~exceptions.EnvironmentError` and
    :exc:`~subprocess.CalledProcessError` if you call this function.

    Return the version number as single integer.  Raise
    :exc:`~exceptions.ValueError`, if the version number retrieved from udev
    could not be converted to an integer.  Raise
    :exc:`~exceptions.EnvironmentError`, if ``udevadm`` was not found, or could
    not be executed.  Raise :exc:`subprocess.CalledProcessError`, if
    ``udevadm`` returned a non-zero exit code.  On Python 2.7 or newer, the
    ``output`` attribute of this exception is correctly set.

    .. versionadded:: 0.8
    """
    output = ensure_unicode_string(check_output(['udevadm', '--version']))
    return int(output.strip())
_compat.py000064400000002674150351420040006543 0ustar00# -*- coding: utf-8 -*-
# Copyright (C) 2011 Sebastian Wiesner <lunaryorn@gmail.com>

# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.

# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
# for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA


"""
    pyudev._compat
    ==============

    Compatibility for Python versions, that lack certain functions.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
"""


from __future__ import (print_function, division, unicode_literals,
                        absolute_import)

from subprocess import Popen, CalledProcessError, PIPE


def check_output(command):
    """
    Compatibility with :func:`subprocess.check_output` from Python 2.7 and
    upwards.
    """
    proc = Popen(command, stdout=PIPE)
    output = proc.communicate()[0]
    if proc.returncode != 0:
        raise CalledProcessError(proc.returncode, command)
    return output
__pycache__/version.cpython-36.opt-1.pyc000064400000001143150351420040014017 0ustar003

u1�WM�@sHdZdZddjdd�edd	�D��djd
d�ed	d�D��fZdS)zx
    pyudev.version
    ==============

    Version information.

    .. moduleauthor::  mulhern  <amulhern@redhat.com>
���z%s%s�.ccs|]}t|�VqdS)N)�str)�.0�x�r�/usr/lib/python3.6/version.py�	<genexpr>sr
N�ccs|]}t|�VqdS)N)r)rrrrr	r
 s)rrrr)�__doc__Z__version_info__�join�__version__rrrr	�<module>s__pycache__/_util.cpython-36.opt-1.pyc000064400000013502150351420040013450 0ustar003

N�#W(�@s�dZddlmZmZmZmZyddlmZWn ek
rLddl	mZYnXddl
Z
ddlZddlZddl
Z
ddlZdd�Zdd�Zd	d
�Zdd�Zd
d�Zdd�Zdd�Zdd�ZdS)z|
    pyudev._util
    ============

    Internal utilities

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
�)�print_function�division�unicode_literals�absolute_import)�check_outputNcCst|t�s|jtj��}|S)z�
    Return the given ``value`` as bytestring.

    If the given ``value`` is not a byte string, but a real unicode string, it
    is encoded with the filesystem encoding (as in
    :func:`sys.getfilesystemencoding()`).
    )�
isinstance�bytes�encode�sys�getfilesystemencoding)�value�r
�/usr/lib/python3.6/_util.py�ensure_byte_string-s
rcCst|tj�s|jtj��}|S)z�
    Return the given ``value`` as unicode string.

    If the given ``value`` is not a unicode string, but a byte string, it is
    decoded with the filesystem encoding (as in
    :func:`sys.getfilesystemencoding()`).
    )r�six�	text_type�decoder
r)rr
r
r�ensure_unicode_string:srcCs2t|t�rt|�}t|t�r |Sttj|��SdS)a�
    Return a byte string, which represents the given ``value`` in a way
    suitable as raw value of an udev property.

    If ``value`` is a boolean object, it is converted to ``'1'`` or ``'0'``,
    depending on whether ``value`` is ``True`` or ``False``.  If ``value`` is a
    byte string already, it is returned unchanged.  Anything else is simply
    converted to a unicode string, and then passed to
    :func:`ensure_byte_string`.
    N)r�bool�intrrrr)rr
r
r�property_value_to_bytesGs


rcCs|dkrtdj|���|dkS)z�
    Convert the given unicode string ``value`` to a boolean object.

    If ``value`` is ``'1'``, ``True`` is returned.  If ``value`` is ``'0'``,
    ``False`` is returned.  Any other value raises a
    :exc:`~exceptions.ValueError`.
    �1�0zNot a boolean value: {0!r})rr)�
ValueError�format)rr
r
r�string_to_bool\srccs6x0|r0|j|�}|j|�}||fV|j|�}qWdS)z�
    Iteration helper for udev list entry objects.

    Yield a tuple ``(name, value)``.  ``name`` and ``value`` are bytestrings
    containing the name and the value of the list entry.  The exact contents
    depend on the list iterated over.
    N)Zudev_list_entry_get_nameZudev_list_entry_get_valueZudev_list_entry_get_next)Zlibudev�entry�namerr
r
r�udev_list_iterateis



rcCs:tj|�j}tj|�rdStj|�r(dStdj|���dS)a�
    Get the device type of a device file.

    ``filename`` is a string containing the path of a device file.

    Return ``'char'`` if ``filename`` is a character device, or ``'block'`` if
    ``filename`` is a block device.  Raise :exc:`~exceptions.ValueError` if
    ``filename`` is no device file at all.  Raise
    :exc:`~exceptions.EnvironmentError` if ``filename`` does not exist or if
    its metadata was inaccessible.

    .. versionadded:: 0.15
    �char�blockznot a device file: {0!r}N)�os�stat�st_mode�S_ISCHR�S_ISBLKrr)�filename�moder
r
r�get_device_typexs

r(cOsvddl}xhy
|||�Stt|jfk
rl}z4t|ttf�rD|j}n
|jd}|tjkrZw
�WYdd}~Xq
Xq
WdS)a=
    Handle interruptions to an interruptible system call.

    Run an interruptible system call in a loop and retry if it raises EINTR.
    The signal calls that may raise EINTR prior to Python 3.5 are listed in
    PEP 0475.  Any calls to these functions must be wrapped in eintr_retry_call
    in order to handle EINTR returns in older versions of Python.

    This function is safe to use under Python 3.5 and newer since the wrapped
    function will simply return without raising EINTR.

    This function is based on _eintr_retry_call in python's subprocess.py.
    rN)�select�OSError�IOError�errorr�errno�argsZEINTR)�funcr.�kwargsr)�errZ
error_coder
r
r�eintr_retry_call�s


r2cCsttddg��}t|j��S)ak
    Get the version of the underlying udev library.

    udev doesn't use a standard major-minor versioning scheme, but instead
    labels releases with a single consecutive number.  Consequently, the
    version number returned by this function is a single integer, and not a
    tuple (like for instance the interpreter version in
    :data:`sys.version_info`).

    As libudev itself does not provide a function to query the version number,
    this function calls the ``udevadm`` utility, so be prepared to catch
    :exc:`~exceptions.EnvironmentError` and
    :exc:`~subprocess.CalledProcessError` if you call this function.

    Return the version number as single integer.  Raise
    :exc:`~exceptions.ValueError`, if the version number retrieved from udev
    could not be converted to an integer.  Raise
    :exc:`~exceptions.EnvironmentError`, if ``udevadm`` was not found, or could
    not be executed.  Raise :exc:`subprocess.CalledProcessError`, if
    ``udevadm`` returned a non-zero exit code.  On Python 2.7 or newer, the
    ``output`` attribute of this exception is correctly set.

    .. versionadded:: 0.8
    Zudevadmz	--version)rrr�strip)�outputr
r
r�udev_version�sr5)�__doc__Z
__future__rrrr�
subprocessr�ImportErrorZpyudev._compatr!r
r"r-rrrrrrr(r2r5r
r
r
r�<module>s$


!__pycache__/discover.cpython-36.pyc000064400000032356150351420040013223 0ustar003

u1�W�,�@s�dZddlmZddlmZddlmZddlmZddlZddlZddlZddl	Z	ddl
Z
ddlmZddlm
Z
d	d
�Ze
jej�Gdd�de��ZGd
d�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZdS)z�
    pyudev.discover
    ===============

    Tools to discover a device given limited information.

    .. moduleauthor::  mulhern <amulhern@redhat.com>
�)�absolute_import)�division)�print_function)�unicode_literalsN)�Devices)�DeviceNotFoundErrorcstj���fdd��}|S)z\
    Allow Device discovery methods to return None instead of raising an
    exception.
    cs$y
�||�Stk
rdSXdS)z�
        Returns result of calling ``func`` on ``args``, ``kwargs``.
        Returns None if ``func`` raises :exc:`DeviceNotFoundError`.
        N)r)�args�kwargs)�func��/usr/lib/python3.6/discover.py�the_func1s
z wrap_exception.<locals>.the_func)�	functools�wraps)r
r
r)r
r�wrap_exception+src@sLeZdZdZeejdd���Zeejdd���Zedd��Z	edd	��Z
d
S)�
HypothesiszM
    Represents a hypothesis about the meaning of the device identifier.
    cCs
t��dS)a�
        Match the given string according to the hypothesis.

        The purpose of this method is to obtain a value corresponding to
        ``value`` if that is possible. It may use a regular expression, but
        in general it should just return ``value`` and let the lookup method
        sort out the rest.

        :param str value: the string to inspect
        :returns: the matched thing or None if unmatched
        :rtype: the type of lookup's key parameter or NoneType
        N)�NotImplementedError)�cls�valuerrr�matchDszHypothesis.matchcCs
t��dS)aN
        Lookup the given string according to the hypothesis.

        :param Context context: the pyudev context
        :param key: a key with which to lookup the device
        :type key: the type of match's return value if not None
        :returns: a list of Devices obtained
        :rtype: frozenset of :class:`Device`
        N)r)r�context�keyrrr�lookupUszHypothesis.lookupcCsdS)z�
        A potentially expensive method that may allow an :class:`Hypothesis`
        to find devices more rapidly or to find a device that it would
        otherwise miss.

        :param Context context: the pyudev context
        Nr)rrrrr�setupcs	zHypothesis.setupcCs$|j|�}|dk	r|j||�St�S)a
        Get any devices that may correspond to the given string.

        :param Context context: the pyudev context
        :param str value: the value to look for
        :returns: a list of devices obtained
        :rtype: set of :class:`Device`
        N)rr�	frozenset)rrrrrrr�get_devicesns

zHypothesis.get_devicesN)�__name__�
__module__�__qualname__�__doc__�classmethod�abc�abstractmethodrrrrrrrrr>s
rc@sLeZdZdZedd��Zedd��Zedd��Zedd	��Zed
d��Z	dS)
�DeviceNumberHypothesisz�
    Represents the hypothesis that the device is a device number.

    The device may be separated into major/minor number or a composite number.
    cCs8tjd�}|j|�}|o6tjt|jd��t|jd���S)z�
        Match the number under the assumption that it is a major,minor pair.

        :param str value: value to match
        :returns: the device number or None
        :rtype: int or NoneType
        z#^(?P<major>\d+)(\D+)(?P<minor>\d+)$�major�minor)�re�compiler�os�makedev�int�group)rrZmajor_minor_rerrrr�_match_major_minor�s	
z)DeviceNumberHypothesis._match_major_minorcCs&tjd�}|j|�}|o$t|jd��S)z�
        Match the number under the assumption that it is a single number.

        :param str value: value to match
        :returns: the device number or None
        :rtype: int or NoneType
        z^(?P<number>\d+)$Znumber)r&r'rr*r+)rrZ	number_rerrrr�
_match_number�s	

z$DeviceNumberHypothesis._match_numbercCs|j|�p|j|�S)z�
        Match the number under the assumption that it is a device number.

        :returns: the device number or None
        :rtype: int or NoneType
        )r,r-)rrrrrr�szDeviceNumberHypothesis.matchcCs|j}tjtjj|d��S)z�
        Find subsystems in /sys/dev.

        :param Context context: the context
        :returns: a lis of available subsystems
        :rtype: list of str
        Zdev)�sys_pathr(�listdir�path�join)rrr.rrr�find_subsystems�s	z&DeviceNumberHypothesis.find_subsystemscs8ttj�����fdd�|j��D�}tdd�|D��S)z�
        Lookup by the device number.

        :param Context context: the context
        :param int key: the device number
        :returns: a list of matching devices
        :rtype: frozenset of :class:`Device`
        c3s|]}��|��VqdS)Nr)�.0�s)rr
rrr�	<genexpr>�sz0DeviceNumberHypothesis.lookup.<locals>.<genexpr>css|]}|dk	r|VqdS)Nr)r3�rrrrr5�s)rrZfrom_device_numberr2r)rrr�resr)rr
rrr�s

zDeviceNumberHypothesis.lookupN)
rrrrr r,r-rr2rrrrrr#|s

r#c@s(eZdZdZedd��Zedd��ZdS)�DevicePathHypothesiszG
    Discover the device assuming the identifier is a device path.
    cCs|S)z�
        Match ``value`` under the assumption that it is a device path.

        :returns: the device path or None
        :rtype: str or NoneType
        r)rrrrrr�szDevicePathHypothesis.matchcCs(ttj�||�}|dk	r"t|f�St�S)z�
        Lookup by the path.

        :param Context context: the context
        :param str key: the device path
        :returns: a list of matching devices
        :rtype: frozenset of :class:`Device`
        N)rrZ	from_pathr)rrrr7rrrr�s
zDevicePathHypothesis.lookupN)rrrrr rrrrrrr8�s
r8c@s4eZdZdZedd��Zedd��Zedd��ZdS)	�DeviceNameHypothesiszf
    Discover the device assuming the input is a device name.

    Try every available subsystem.
    cs<|j�d}�fdd�|D�}dd�|D�}tdd�|D��S)	z�
        Find all subsystems in sysfs.

        :param Context context: the context
        :rtype: frozenset
        :returns: subsystems in sysfs
        �bus�class�	subsystemc3s|]}tjj�|�VqdS)N)r(r0r1)r3�name)r.rrr5�sz7DeviceNameHypothesis.find_subsystems.<locals>.<genexpr>css|]}tjj|�r|VqdS)N)r(r0�isdir)r3�drrrr5�scss"|]}tj|�D]
}|VqqdS)N)r(r/)r3r?�nrrrr5�s)r:r;r<)r.r)rrZdirnamesZabsnamesZ	realnamesr)r.rr2�s
	z$DeviceNameHypothesis.find_subsystemscCs|S)z�
        Match ``value`` under the assumption that it is a device name.

        :returns: the device path or None
        :rtype: str or NoneType
        r)rrrrrr�szDeviceNameHypothesis.matchcs8ttj�����fdd�|j��D�}tdd�|D��S)z�
        Lookup by the path.

        :param Context context: the context
        :param str key: the device path
        :returns: a list of matching devices
        :rtype: frozenset of :class:`Device`
        c3s|]}��|��VqdS)Nr)r3r4)rr
rrrr5sz.DeviceNameHypothesis.lookup.<locals>.<genexpr>css|]}|dk	r|VqdS)Nr)r3r6rrrr5s)rr�	from_namer2r)rrrr7r)rr
rrrs

zDeviceNameHypothesis.lookupN)rrrrr r2rrrrrrr9�s
r9c@sZeZdZdZdddddddd	d
ddgZed
d��Zedd��Zedd��Zedd��Z	dS)�DeviceFileHypothesisz�
    Discover the device assuming the value is some portion of a device file.

    The device file may be a link to a device node.
    z/devz/dev/disk/by-idz/dev/disk/by-labelz/dev/disk/by-partlabelz/dev/disk/by-partuuidz/dev/disk/by-pathz/dev/disk/by-uuidz/dev/input/by-pathz/dev/mapperz/dev/mdz/dev/vgcCs:|j�}dd�|D�}dd�|D�}ttdd�|D���S)a7
        Get all directories that may contain links to device nodes.

        This method checks the device links of every device, so it is very
        expensive.

        :param Context context: the context
        :returns: a sorted list of directories that contain device links
        :rtype: list
        css|]}t|j�r|VqdS)N)�list�device_links)r3r?rrrr55sz5DeviceFileHypothesis.get_link_dirs.<locals>.<genexpr>css|]}|jD]
}|VqqdS)N)rD)r3r?�lrrrr56scss|]}tjj|�VqdS)N)r(r0�dirname)r3rErrrr57s)Zlist_devices�sorted�set)rr�devicesZdevices_with_linksZlinksrrr�
get_link_dirs(sz"DeviceFileHypothesis.get_link_dirscCs|j|�|_dS)z�
        Set the link directories to be used when discovering by file.

        Uses `get_link_dirs`, so is as expensive as it is.

        :param Context context: the context
        N)rJ�
_LINK_DIRS)rrrrrr9s	zDeviceFileHypothesis.setupcCs|S)Nr)rrrrrrDszDeviceFileHypothesis.matchcsrttj��d�kr4����}|dk	r.t|f�St�S�fdd�|jD�}��fdd�|D�}tdd�|D��SdS)a�
        Lookup the device under the assumption that the key is part of
        the name of a device file.

        :param Context context: the context
        :param str key: a portion of the device file name

        It is assumed that either it is the whole name of the device file
        or it is the basename.

        A device file may be a device node or a device link.
        �/Nc3s|]}tjj|��VqdS)N)r(r0r1)r3Zld)rrrr5[sz.DeviceFileHypothesis.lookup.<locals>.<genexpr>c3s|]}��|�VqdS)Nr)r3�f)rr
rrr5\scss|]}|dk	r|VqdS)Nr)r3r?rrrr5]s)rrZfrom_device_filerrK)rrrZdevice�filesrIr)rr
rrrHs

zDeviceFileHypothesis.lookupN)
rrrrrKr rJrrrrrrrrBs rBc@s4eZdZdZeeeegZdd�Z	dd�Z
dd�ZdS)	�	Discoveryz1
    Provides discovery methods for devices.
    cCs|j|_dS)N)�_HYPOTHESES�_hypotheses)�selfrrr�__init__mszDiscovery.__init__cCsx|jD]}|j|�qWdS)z
        Set up individual hypotheses.

        May be an expensive call.

        :param Context context: the context
        N)rQr)rRrZhyprrrrpszDiscovery.setupcst��fdd�|jD��S)z�
        Get the devices corresponding to value.

        :param Context context: the context
        :param str value: some identifier of the device
        :returns: a list of corresponding devices
        :rtype: frozenset of :class:`Device`
        c3s$|]}|j���D]
}|VqqdS)N)r)r3�hr?)rrrrr5�sz(Discovery.get_devices.<locals>.<genexpr>)rrQ)rRrrr)rrrr{s	zDiscovery.get_devicesN)rrrrrBr9r#r8rPrSrrrrrrrO`srO)rZ
__future__rrrrr!rr(r&ZsixZ
pyudev.devicerrrZ
add_metaclass�ABCMeta�objectrr#r8r9rBrOrrrr�<module>s&=K/M__pycache__/core.cpython-36.pyc000064400000031216150351420040012327 0ustar003

u1�Ws4�@s�dZddlmZmZmZmZddlmZddlm	Z	ddl
mZddl
mZddl
mZddlmZdd	lmZdd
lmZddlmZGdd
�d
e�ZGdd�de�ZdS)z�
    pyudev.core
    ===========

    Core types and functions of :mod:`pyudev`.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
�)�print_function�division�unicode_literals�absolute_import)�Devices)�DeviceNotFoundAtPathError)�ERROR_CHECKERS)�
SIGNATURES)�load_ctypes_library)�ensure_byte_string)�ensure_unicode_string)�property_value_to_bytes)�udev_list_iteratec@sfeZdZdZdd�Zdd�Zedd��Zedd	��Zed
d��Z	edd
��Z
e
jdd
��Z
dd�ZdS)�Contexta
    A device database connection.

    This class represents a connection to the udev device database, and is
    really *the* central object to access udev.  You need an instance of this
    class for almost anything else in pyudev.

    This class itself gives access to various udev configuration data (e.g.
    :attr:`sys_path`, :attr:`device_path`), and provides device enumeration
    (:meth:`list_devices()`).

    Instances of this class can directly be given as ``udev *`` to functions
    wrapped through :mod:`ctypes`.
    cCstdtt�|_|jj�|_dS)z'
        Create a new context.
        ZudevN)r
r	r�_libudevZudev_new�_as_parameter_)�self�r�/usr/lib/python3.6/core.py�__init__<szContext.__init__cCs|jj|�dS)N)rZ
udev_unref)rrrr�__del__CszContext.__del__cCs$t|jd�rt|jj|��SdSdS)zV
        The ``sysfs`` mount point defaulting to ``/sys'`` as unicode string.
        �udev_get_sys_pathz/sysN)�hasattrrrr)rrrr�sys_pathFszContext.sys_pathcCs$t|jd�rt|jj|��SdSdS)zU
        The device directory path defaulting to ``/dev`` as unicode string.
        �udev_get_dev_pathz/devN)rrrr)rrrr�device_pathQszContext.device_pathcCs$t|jd�rt|jj|��SdSdS)z�
        The run runtime directory path defaulting to ``/run`` as unicode
        string.

        .. udevversion:: 167

        .. versionadded:: 0.10
        �udev_get_run_pathz	/run/udevN)rrrr)rrrr�run_path\s
zContext.run_pathcCs|jj|�S)a
        The logging priority of the interal logging facitility of udev as
        integer with a standard :mod:`syslog` priority.  Assign to this
        property to change the logging priority.

        UDev uses the standard :mod:`syslog` priorities.  Constants for these
        priorities are defined in the :mod:`syslog` module in the standard
        library:

        >>> import syslog
        >>> context = pyudev.Context()
        >>> context.log_priority = syslog.LOG_DEBUG

        .. versionadded:: 0.9
        )rZudev_get_log_priority)rrrr�log_prioritykszContext.log_prioritycCs|jj||�dS)zT
        Set the log priority.

        :param int value: the log priority.
        N)rZudev_set_log_priority)r�valuerrrr~scKst|�jf|�S)a"
        List all available devices.

        The arguments of this method are the same as for
        :meth:`Enumerator.match()`.  In fact, the arguments are simply passed
        straight to method :meth:`~Enumerator.match()`.

        This function creates and returns an :class:`Enumerator` object,
        that can be used to filter the list of devices, and eventually
        retrieve :class:`Device` objects representing matching devices.

        .. versionchanged:: 0.8
           Accept keyword arguments now for easy matching.
        )�
Enumerator�match)r�kwargsrrr�list_devices�szContext.list_devicesN)
�__name__�
__module__�__qualname__�__doc__rr�propertyrrrr�setterr#rrrrr,s	rc@sleZdZdZdd�Zdd�Zdd�Zdd	d
�Zdd�Zd
d�Z	ddd�Z
dd�Zdd�Zdd�Z
dd�ZdS)r a�
    A filtered iterable of devices.

    To retrieve devices, simply iterate over an instance of this class.
    This operation yields :class:`Device` objects representing the available
    devices.

    Before iteration the device list can be filtered by subsystem or by
    property values using :meth:`match_subsystem` and
    :meth:`match_property`.  Multiple subsystem (property) filters are
    combined using a logical OR, filters of different types are combined
    using a logical AND.  The following filter for instance::

        devices.match_subsystem('block').match_property(
            'ID_TYPE', 'disk').match_property('DEVTYPE', 'disk')

    means the following::

        subsystem == 'block' and (ID_TYPE == 'disk' or DEVTYPE == 'disk')

    Once added, a filter cannot be removed anymore.  Create a new object
    instead.

    Instances of this class can directly be given as given ``udev_enumerate *``
    to functions wrapped through :mod:`ctypes`.
    cCs2t|t�std��||_|jj|�|_|j|_dS)z�
        Create a new enumerator with the given ``context`` (a
        :class:`Context` instance).

        While you can create objects of this class directly, this is not
        recommended.  Call :method:`Context.list_devices()` instead.
        zInvalid context objectN)�
isinstancer�	TypeError�contextrZudev_enumerate_newr)rr,rrrr�s

zEnumerator.__init__cCs|jj|�dS)N)rZudev_enumerate_unref)rrrrr�szEnumerator.__del__cKs�|jdd�}|dk	r|j|�|jdd�}|dk	r<|j|�|jdd�}|dk	rZ|j|�|jdd�}|dk	rx|j|�x |j�D]\}}|j||�q�W|S)a2
        Include devices according to the rules defined by the keyword
        arguments.  These keyword arguments are interpreted as follows:

        - The value for the keyword argument ``subsystem`` is forwarded to
          :meth:`match_subsystem()`.
        - The value for the keyword argument ``sys_name`` is forwared to
          :meth:`match_sys_name()`.
        - The value for the keyword argument ``tag`` is forwared to
          :meth:`match_tag()`.
        - The value for the keyword argument ``parent`` is forwared to
          :meth:`match_parent()`.
        - All other keyword arguments are forwareded one by one to
          :meth:`match_property()`.  The keyword argument itself is interpreted
          as property name, the value of the keyword argument as the property
          value.

        All keyword arguments are optional, calling this method without no
        arguments at all is simply a noop.

        Return the instance again.

        .. versionadded:: 0.8

        .. versionchanged:: 0.13
           Add ``parent`` keyword.
        �	subsystemN�sys_name�tag�parent)�pop�match_subsystem�match_sys_name�	match_tag�match_parent�items�match_property)rr"r-r.r/r0�proprrrrr!�s



zEnumerator.matchFcCs&|r|jjn|jj}||t|��|S)a$
        Include all devices, which are part of the given ``subsystem``.

        ``subsystem`` is either a unicode string or a byte string, containing
        the name of the subsystem.  If ``nomatch`` is ``True`` (default is
        ``False``), the match is inverted:  A device is only included if it is
        *not* part of the given ``subsystem``.

        Note that, if a device has no subsystem, it is not included either
        with value of ``nomatch`` True or with value of ``nomatch`` False.

        Return the instance again.
        )rZ$udev_enumerate_add_nomatch_subsystemZ"udev_enumerate_add_match_subsystemr)rr-�nomatchr!rrrr2�szEnumerator.match_subsystemcCs|jj|t|��|S)z�
        Include all devices with the given name.

        ``sys_name`` is a byte or unicode string containing the device name.

        Return the instance again.

        .. versionadded:: 0.8
        )rZ udev_enumerate_add_match_sysnamer)rr.rrrr3s
zEnumerator.match_sys_namecCs|jj|t|�t|��|S)a�
        Include all devices, whose ``prop`` has the given ``value``.

        ``prop`` is either a unicode string or a byte string, containing
        the name of the property to match.  ``value`` is a property value,
        being one of the following types:

        - :func:`int`
        - :func:`bool`
        - A byte string
        - Anything convertable to a unicode string (including a unicode string
          itself)

        Return the instance again.
        )rZ!udev_enumerate_add_match_propertyrr
)rr8rrrrr7szEnumerator.match_propertycCs,|s|jjn|jj}||t|�t|��|S)a�
        Include all devices, whose ``attribute`` has the given ``value``.

        ``attribute`` is either a unicode string or a byte string, containing
        the name of a sys attribute to match.  ``value`` is an attribute value,
        being one of the following types:

        - :func:`int`,
        - :func:`bool`
        - A byte string
        - Anything convertable to a unicode string (including a unicode string
          itself)

        If ``nomatch`` is ``True`` (default is ``False``), the match is
        inverted:  A device is include if the ``attribute`` does *not* match
        the given ``value``.

        .. note::

           If ``nomatch`` is ``True``, devices which do not have the given
           ``attribute`` at all are also included.  In other words, with
           ``nomatch=True`` the given ``attribute`` is *not* guaranteed to
           exist on all returned devices.

        Return the instance again.
        )rZ udev_enumerate_add_match_sysattrZ"udev_enumerate_add_nomatch_sysattrrr
)rZ	attributerr9r!rrr�match_attribute's


zEnumerator.match_attributecCs|jj|t|��|S)z�
        Include all devices, which have the given ``tag`` attached.

        ``tag`` is a byte or unicode string containing the tag name.

        Return the instance again.

        .. udevversion:: 154

        .. versionadded:: 0.6
        )rZudev_enumerate_add_match_tagr)rr/rrrr4IszEnumerator.match_tagcCs|jj|�|S)a�
        Include only devices, which are initialized.

        Initialized devices have properly set device node permissions and
        context, and are (in case of network devices) fully renamed.

        Currently this will not affect devices which do not have device nodes
        and are not network interfaces.

        Return the instance again.

        .. seealso:: :attr:`Device.is_initialized`

        .. udevversion:: 165

        .. versionadded:: 0.8
        )rZ'udev_enumerate_add_match_is_initialized)rrrr�match_is_initializedXszEnumerator.match_is_initializedcCs|jj||�|S)a 
        Include all devices on the subtree of the given ``parent`` device.

        The ``parent`` device itself is also included.

        ``parent`` is a :class:`~pyudev.Device`.

        Return the instance again.

        .. udevversion:: 172

        .. versionadded:: 0.13
        )rZudev_enumerate_add_match_parent)rr0rrrr5mszEnumerator.match_parentccsb|jj|�|jj|�}xDt|j|�D]4\}}ytj|j|�VWq&tk
rXw&Yq&Xq&WdS)z\
        Iterate over all matching devices.

        Yield :class:`Device` objects.
        N)rZudev_enumerate_scan_devicesZudev_enumerate_get_list_entryrrZ
from_sys_pathr,r)r�entry�name�_rrr�__iter__~szEnumerator.__iter__N)F)F)r$r%r&r'rrr!r2r3r7r:r4r;r5r?rrrrr �s,

"r N)r'Z
__future__rrrrZ
pyudev.devicerZpyudev.device._errorsrZpyudev._ctypeslib.libudevrr	Zpyudev._ctypeslib.utilsr
Zpyudev._utilrrr
r�objectrr rrrr�<module>sm__pycache__/version.cpython-36.pyc000064400000001143150351420040013060 0ustar003

u1�WM�@sHdZdZddjdd�edd	�D��djd
d�ed	d�D��fZdS)zx
    pyudev.version
    ==============

    Version information.

    .. moduleauthor::  mulhern  <amulhern@redhat.com>
���z%s%s�.ccs|]}t|�VqdS)N)�str)�.0�x�r�/usr/lib/python3.6/version.py�	<genexpr>sr
N�ccs|]}t|�VqdS)N)r)rrrrr	r
 s)rrrr)�__doc__Z__version_info__�join�__version__rrrr	�<module>s__pycache__/discover.cpython-36.opt-1.pyc000064400000032356150351420040014162 0ustar003

u1�W�,�@s�dZddlmZddlmZddlmZddlmZddlZddlZddlZddl	Z	ddl
Z
ddlmZddlm
Z
d	d
�Ze
jej�Gdd�de��ZGd
d�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZdS)z�
    pyudev.discover
    ===============

    Tools to discover a device given limited information.

    .. moduleauthor::  mulhern <amulhern@redhat.com>
�)�absolute_import)�division)�print_function)�unicode_literalsN)�Devices)�DeviceNotFoundErrorcstj���fdd��}|S)z\
    Allow Device discovery methods to return None instead of raising an
    exception.
    cs$y
�||�Stk
rdSXdS)z�
        Returns result of calling ``func`` on ``args``, ``kwargs``.
        Returns None if ``func`` raises :exc:`DeviceNotFoundError`.
        N)r)�args�kwargs)�func��/usr/lib/python3.6/discover.py�the_func1s
z wrap_exception.<locals>.the_func)�	functools�wraps)r
r
r)r
r�wrap_exception+src@sLeZdZdZeejdd���Zeejdd���Zedd��Z	edd	��Z
d
S)�
HypothesiszM
    Represents a hypothesis about the meaning of the device identifier.
    cCs
t��dS)a�
        Match the given string according to the hypothesis.

        The purpose of this method is to obtain a value corresponding to
        ``value`` if that is possible. It may use a regular expression, but
        in general it should just return ``value`` and let the lookup method
        sort out the rest.

        :param str value: the string to inspect
        :returns: the matched thing or None if unmatched
        :rtype: the type of lookup's key parameter or NoneType
        N)�NotImplementedError)�cls�valuerrr�matchDszHypothesis.matchcCs
t��dS)aN
        Lookup the given string according to the hypothesis.

        :param Context context: the pyudev context
        :param key: a key with which to lookup the device
        :type key: the type of match's return value if not None
        :returns: a list of Devices obtained
        :rtype: frozenset of :class:`Device`
        N)r)r�context�keyrrr�lookupUszHypothesis.lookupcCsdS)z�
        A potentially expensive method that may allow an :class:`Hypothesis`
        to find devices more rapidly or to find a device that it would
        otherwise miss.

        :param Context context: the pyudev context
        Nr)rrrrr�setupcs	zHypothesis.setupcCs$|j|�}|dk	r|j||�St�S)a
        Get any devices that may correspond to the given string.

        :param Context context: the pyudev context
        :param str value: the value to look for
        :returns: a list of devices obtained
        :rtype: set of :class:`Device`
        N)rr�	frozenset)rrrrrrr�get_devicesns

zHypothesis.get_devicesN)�__name__�
__module__�__qualname__�__doc__�classmethod�abc�abstractmethodrrrrrrrrr>s
rc@sLeZdZdZedd��Zedd��Zedd��Zedd	��Zed
d��Z	dS)
�DeviceNumberHypothesisz�
    Represents the hypothesis that the device is a device number.

    The device may be separated into major/minor number or a composite number.
    cCs8tjd�}|j|�}|o6tjt|jd��t|jd���S)z�
        Match the number under the assumption that it is a major,minor pair.

        :param str value: value to match
        :returns: the device number or None
        :rtype: int or NoneType
        z#^(?P<major>\d+)(\D+)(?P<minor>\d+)$�major�minor)�re�compiler�os�makedev�int�group)rrZmajor_minor_rerrrr�_match_major_minor�s	
z)DeviceNumberHypothesis._match_major_minorcCs&tjd�}|j|�}|o$t|jd��S)z�
        Match the number under the assumption that it is a single number.

        :param str value: value to match
        :returns: the device number or None
        :rtype: int or NoneType
        z^(?P<number>\d+)$Znumber)r&r'rr*r+)rrZ	number_rerrrr�
_match_number�s	

z$DeviceNumberHypothesis._match_numbercCs|j|�p|j|�S)z�
        Match the number under the assumption that it is a device number.

        :returns: the device number or None
        :rtype: int or NoneType
        )r,r-)rrrrrr�szDeviceNumberHypothesis.matchcCs|j}tjtjj|d��S)z�
        Find subsystems in /sys/dev.

        :param Context context: the context
        :returns: a lis of available subsystems
        :rtype: list of str
        Zdev)�sys_pathr(�listdir�path�join)rrr.rrr�find_subsystems�s	z&DeviceNumberHypothesis.find_subsystemscs8ttj�����fdd�|j��D�}tdd�|D��S)z�
        Lookup by the device number.

        :param Context context: the context
        :param int key: the device number
        :returns: a list of matching devices
        :rtype: frozenset of :class:`Device`
        c3s|]}��|��VqdS)Nr)�.0�s)rr
rrr�	<genexpr>�sz0DeviceNumberHypothesis.lookup.<locals>.<genexpr>css|]}|dk	r|VqdS)Nr)r3�rrrrr5�s)rrZfrom_device_numberr2r)rrr�resr)rr
rrr�s

zDeviceNumberHypothesis.lookupN)
rrrrr r,r-rr2rrrrrr#|s

r#c@s(eZdZdZedd��Zedd��ZdS)�DevicePathHypothesiszG
    Discover the device assuming the identifier is a device path.
    cCs|S)z�
        Match ``value`` under the assumption that it is a device path.

        :returns: the device path or None
        :rtype: str or NoneType
        r)rrrrrr�szDevicePathHypothesis.matchcCs(ttj�||�}|dk	r"t|f�St�S)z�
        Lookup by the path.

        :param Context context: the context
        :param str key: the device path
        :returns: a list of matching devices
        :rtype: frozenset of :class:`Device`
        N)rrZ	from_pathr)rrrr7rrrr�s
zDevicePathHypothesis.lookupN)rrrrr rrrrrrr8�s
r8c@s4eZdZdZedd��Zedd��Zedd��ZdS)	�DeviceNameHypothesiszf
    Discover the device assuming the input is a device name.

    Try every available subsystem.
    cs<|j�d}�fdd�|D�}dd�|D�}tdd�|D��S)	z�
        Find all subsystems in sysfs.

        :param Context context: the context
        :rtype: frozenset
        :returns: subsystems in sysfs
        �bus�class�	subsystemc3s|]}tjj�|�VqdS)N)r(r0r1)r3�name)r.rrr5�sz7DeviceNameHypothesis.find_subsystems.<locals>.<genexpr>css|]}tjj|�r|VqdS)N)r(r0�isdir)r3�drrrr5�scss"|]}tj|�D]
}|VqqdS)N)r(r/)r3r?�nrrrr5�s)r:r;r<)r.r)rrZdirnamesZabsnamesZ	realnamesr)r.rr2�s
	z$DeviceNameHypothesis.find_subsystemscCs|S)z�
        Match ``value`` under the assumption that it is a device name.

        :returns: the device path or None
        :rtype: str or NoneType
        r)rrrrrr�szDeviceNameHypothesis.matchcs8ttj�����fdd�|j��D�}tdd�|D��S)z�
        Lookup by the path.

        :param Context context: the context
        :param str key: the device path
        :returns: a list of matching devices
        :rtype: frozenset of :class:`Device`
        c3s|]}��|��VqdS)Nr)r3r4)rr
rrrr5sz.DeviceNameHypothesis.lookup.<locals>.<genexpr>css|]}|dk	r|VqdS)Nr)r3r6rrrr5s)rr�	from_namer2r)rrrr7r)rr
rrrs

zDeviceNameHypothesis.lookupN)rrrrr r2rrrrrrr9�s
r9c@sZeZdZdZdddddddd	d
ddgZed
d��Zedd��Zedd��Zedd��Z	dS)�DeviceFileHypothesisz�
    Discover the device assuming the value is some portion of a device file.

    The device file may be a link to a device node.
    z/devz/dev/disk/by-idz/dev/disk/by-labelz/dev/disk/by-partlabelz/dev/disk/by-partuuidz/dev/disk/by-pathz/dev/disk/by-uuidz/dev/input/by-pathz/dev/mapperz/dev/mdz/dev/vgcCs:|j�}dd�|D�}dd�|D�}ttdd�|D���S)a7
        Get all directories that may contain links to device nodes.

        This method checks the device links of every device, so it is very
        expensive.

        :param Context context: the context
        :returns: a sorted list of directories that contain device links
        :rtype: list
        css|]}t|j�r|VqdS)N)�list�device_links)r3r?rrrr55sz5DeviceFileHypothesis.get_link_dirs.<locals>.<genexpr>css|]}|jD]
}|VqqdS)N)rD)r3r?�lrrrr56scss|]}tjj|�VqdS)N)r(r0�dirname)r3rErrrr57s)Zlist_devices�sorted�set)rr�devicesZdevices_with_linksZlinksrrr�
get_link_dirs(sz"DeviceFileHypothesis.get_link_dirscCs|j|�|_dS)z�
        Set the link directories to be used when discovering by file.

        Uses `get_link_dirs`, so is as expensive as it is.

        :param Context context: the context
        N)rJ�
_LINK_DIRS)rrrrrr9s	zDeviceFileHypothesis.setupcCs|S)Nr)rrrrrrDszDeviceFileHypothesis.matchcsrttj��d�kr4����}|dk	r.t|f�St�S�fdd�|jD�}��fdd�|D�}tdd�|D��SdS)a�
        Lookup the device under the assumption that the key is part of
        the name of a device file.

        :param Context context: the context
        :param str key: a portion of the device file name

        It is assumed that either it is the whole name of the device file
        or it is the basename.

        A device file may be a device node or a device link.
        �/Nc3s|]}tjj|��VqdS)N)r(r0r1)r3Zld)rrrr5[sz.DeviceFileHypothesis.lookup.<locals>.<genexpr>c3s|]}��|�VqdS)Nr)r3�f)rr
rrr5\scss|]}|dk	r|VqdS)Nr)r3r?rrrr5]s)rrZfrom_device_filerrK)rrrZdevice�filesrIr)rr
rrrHs

zDeviceFileHypothesis.lookupN)
rrrrrKr rJrrrrrrrrBs rBc@s4eZdZdZeeeegZdd�Z	dd�Z
dd�ZdS)	�	Discoveryz1
    Provides discovery methods for devices.
    cCs|j|_dS)N)�_HYPOTHESES�_hypotheses)�selfrrr�__init__mszDiscovery.__init__cCsx|jD]}|j|�qWdS)z
        Set up individual hypotheses.

        May be an expensive call.

        :param Context context: the context
        N)rQr)rRrZhyprrrrpszDiscovery.setupcst��fdd�|jD��S)z�
        Get the devices corresponding to value.

        :param Context context: the context
        :param str value: some identifier of the device
        :returns: a list of corresponding devices
        :rtype: frozenset of :class:`Device`
        c3s$|]}|j���D]
}|VqqdS)N)r)r3�hr?)rrrrr5�sz(Discovery.get_devices.<locals>.<genexpr>)rrQ)rRrrr)rrrr{s	zDiscovery.get_devicesN)rrrrrBr9r#r8rPrSrrrrrrrO`srO)rZ
__future__rrrrr!rr(r&ZsixZ
pyudev.devicerrrZ
add_metaclass�ABCMeta�objectrr#r8r9rBrOrrrr�<module>s&=K/M__pycache__/_qt_base.cpython-36.pyc000064400000014331150351420040013153 0ustar003

u1�Wk�@s�dZddlmZddlmZddlmZddlmZddlZddlmZGdd	�d	e	�Z
Gd
d�de
�Zdd
�ZGdd�de	�Z
Gdd�de	�ZdS)z�
    pyudev._qt_base
    ===============

    Base mixin class for Qt4,Qt5 support.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
�)�absolute_import)�division)�print_function)�unicode_literalsN)�Devicec@sBeZdZdZdd�Zedd��Zejdd��Zdd�Zd	d
�Z	dS)�MonitorObserverMixinz0
    Base mixin for pyqt monitor observers.
    cCs2||_||j�|j|�|_|jjtj|j�dS)N)�monitor�filenoZRead�notifierZ	activated�intZconnect�_process_udev_event)�selfr�notifier_class�r�/usr/lib/python3.6/_qt_base.py�_setup_notifier+sz$MonitorObserverMixin._setup_notifiercCs
|jj�S)aY
        Whether this observer is enabled or not.

        If ``True`` (the default), this observer is enabled, and emits events.
        Otherwise it is disabled and does not emit any events.  This merely
        reflects the state of the ``enabled`` property of the underlying
        :attr:`notifier`.

        .. versionadded:: 0.14
        )r
Z	isEnabled)r
rrr�enabled1szMonitorObserverMixin.enabledcCs|jj|�dS)N)r
Z
setEnabled)r
�valuerrrr?scCs$|jjdd�}|dk	r |j|�dS)z�
        Attempt to receive a single device event from the monitor, process
        the event and emit corresponding signals.

        Called by ``QSocketNotifier``, if data is available on the udev
        monitoring socket.
        r)ZtimeoutN)rZpoll�_emit_event)r
�devicerrrrCsz(MonitorObserverMixin._process_udev_eventcCs|jj|�dS)N)�deviceEvent�emit)r
rrrrrOsz MonitorObserverMixin._emit_eventN)
�__name__�
__module__�__qualname__�__doc__r�propertyr�setterrrrrrrr%src@s eZdZdZdd�Zdd�ZdS)�QUDevMonitorObserverMixinz*
    Obsolete monitor observer mixin.
    cCs>tj|||�|j|j|j|jd�|_ddl}|jdt	�dS)N)�add�removeZchangeZmoverzAWill be removed in 1.0. Use pyudev.pyqt4.MonitorObserver instead.)
rr�deviceAdded�
deviceRemoved�
deviceChanged�deviceMoved�_action_signal_map�warnings�warn�DeprecationWarning)r
rrr&rrrrYsz)QUDevMonitorObserverMixin._setup_notifiercCs4|jj|j|�|jj|j�}|dk	r0|j|�dS)N)rr�actionr%�get)r
r�signalrrrrdsz%QUDevMonitorObserverMixin._emit_eventN)rrrrrrrrrrrSsrcsd��fdd�	}|S)a
    Generates an initializer to observer the given ``monitor``
    (a :class:`~pyudev.Monitor`):

    ``parent`` is the parent :class:`~PyQt{4,5}.QtCore.QObject` of this
    object.  It is passed unchanged to the inherited constructor of
    :class:`~PyQt{4,5}.QtCore.QObject`.
    Ncs�j||�|j|��dS)N)�__init__r)r
r�parent)�qobject�socket_notifierrrr,tszmake_init.<locals>.__init__)Nr)r.r/r,r)r.r/r�	make_initjs
r0c@seZdZdZedd��ZdS)�MonitorObserverGeneratorz4
    Class to generate a MonitorObserver class.
    cCs.ttd�|tftd�t||�td�|t�i�S)aGenerates an observer for device events integrating into the
        PyQt{4,5} mainloop.

        This class inherits :class:`~PyQt{4,5}.QtCore.QObject` to turn device
        events into Qt signals:

        >>> from pyudev import Context, Monitor
        >>> from pyudev.pyqt4 import MonitorObserver
        >>> context = Context()
        >>> monitor = Monitor.from_netlink(context)
        >>> monitor.filter_by(subsystem='input')
        >>> observer = MonitorObserver(monitor)
        >>> def device_event(device):
        ...     print('event {0} on device {1}'.format(device.action, device))
        >>> observer.deviceEvent.connect(device_event)
        >>> monitor.start()

        This class is a child of :class:`~{PySide, PyQt{4,5}}.QtCore.QObject`.

        ZMonitorObserverr,r)�type�strrr0r)r.r+r/rrr�make_monitor_observer�s
z.MonitorObserverGenerator.make_monitor_observerN)rrrr�staticmethodr4rrrrr1|sr1c@seZdZdZedd��ZdS)�QUDevMonitorObserverGeneratorz4
    Class to generate a MonitorObserver class.
    cCsbttd�|tftd�t||�td�|tjt�td�|t�td�|t�td�|t�td�|t�i�S)aGenerates an observer for device events integrating into the
        PyQt{4,5} mainloop.

        This class inherits :class:`~PyQt{4,5}.QtCore.QObject` to turn device
        events into Qt signals:

        >>> from pyudev import Context, Monitor
        >>> from pyudev.pyqt4 import MonitorObserver
        >>> context = Context()
        >>> monitor = Monitor.from_netlink(context)
        >>> monitor.filter_by(subsystem='input')
        >>> observer = MonitorObserver(monitor)
        >>> def device_event(device):
        ...     print('event {0} on device {1}'.format(device.action, device))
        >>> observer.deviceEvent.connect(device_event)
        >>> monitor.start()

        This class is a child of :class:`~{PyQt{4,5}, PySide}.QtCore.QObject`.

        ZQUDevMonitorObserverr,rr!r"r#r$)r2r3rr0�sixZ	text_typer)r.r+r/rrrr4�sz3QUDevMonitorObserverGenerator.make_monitor_observerN)rrrrr5r4rrrrr6�sr6)rZ
__future__rrrrr7Z
pyudev.devicer�objectrrr0r1r6rrrr�<module>s.'__pycache__/monitor.cpython-36.pyc000064400000046361150351420040013075 0ustar003

u1�W�Q�@s�dZddlmZmZmZmZddlZddlZddlm	Z	ddl
mZddlm
Z
ddlmZddlmZdd	lmZdd
lmZGdd�de�ZGd
d�de	�ZdS)z�
    pyudev.monitor
    ==============

    Monitor implementation.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
�)�print_function�division�unicode_literals�absolute_importN)�Thread)�partial)�Device)�eintr_retry_call)�ensure_byte_string)�pipe)�pollc@s�eZdZdZdd�Zdd�Zed"dd��Zed	d
��Z	dd�Z
d#dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zd$dd�Zdd�Zd d!�Zd
S)%�Monitorat
    A synchronous device event monitor.

    A :class:`Monitor` objects connects to the udev daemon and listens for
    changes to the device list.  A monitor is created by connecting to the
    kernel daemon through netlink (see :meth:`from_netlink`):

    >>> from pyudev import Context, Monitor
    >>> context = Context()
    >>> monitor = Monitor.from_netlink(context)

    Once the monitor is created, you can add a filter using :meth:`filter_by()`
    or :meth:`filter_by_tag()` to drop incoming events in subsystems, which are
    not of interest to the application:

    >>> monitor.filter_by('input')

    When the monitor is eventually set up, you can either poll for events
    synchronously:

    >>> device = monitor.poll(timeout=3)
    >>> if device:
    ...     print('{0.action}: {0}'.format(device))
    ...

    Or you can monitor events asynchronously with :class:`MonitorObserver`.

    To integrate into various event processing frameworks, the monitor provides
    a :func:`selectable <select.select>` file description by :meth:`fileno()`.
    However, do *not*  read or write directly on this file descriptor.

    Instances of this class can directly be given as ``udev_monitor *`` to
    functions wrapped through :mod:`ctypes`.

    .. versionchanged:: 0.16
       Remove :meth:`from_socket()` which is deprecated, and even removed in
       recent udev versions.
    cCs||_||_|j|_d|_dS)NF)�contextZ_as_parameter_�_libudev�_started)�selfrZ	monitor_p�r�/usr/lib/python3.6/monitor.py�__init__VszMonitor.__init__cCs|jj|�dS)N)rZudev_monitor_unref)rrrr�__del__\szMonitor.__del__�udevcCs>|dkrtdj|���|jj|t|��}|s4td��|||�S)a�
        Create a monitor by connecting to the kernel daemon through netlink.

        ``context`` is the :class:`Context` to use.  ``source`` is a string,
        describing the event source.  Two sources are available:

        ``'udev'`` (the default)
          Events emitted after udev as registered and configured the device.
          This is the absolutely recommended source for applications.

        ``'kernel'``
          Events emitted directly after the kernel has seen the device.  The
          device has not yet been configured by udev and might not be usable
          at all.  **Never** use this, unless you know what you are doing.

        Return a new :class:`Monitor` object, which is connected to the
        given source.  Raise :exc:`~exceptions.ValueError`, if an invalid
        source has been specified.  Raise
        :exc:`~exceptions.EnvironmentError`, if the creation of the monitor
        failed.
        �kernelrz8Invalid source: {0!r}. Must be one of "udev" or "kernel"zCould not create udev monitor)rr)�
ValueError�formatrZudev_monitor_new_from_netlinkr
�EnvironmentError)�clsr�source�monitorrrr�from_netlink_szMonitor.from_netlinkcCs|jS)z�
        ``True``, if this monitor was started, ``False`` otherwise. Readonly.

        .. seealso:: :meth:`start()`
        .. versionadded:: 0.16
        )r)rrrr�startedszMonitor.startedcCs|jj|�S)z�
        Return the file description associated with this monitor as integer.

        This is really a real file descriptor ;), which can be watched and
        :func:`select.select`\ ed.
        )rZudev_monitor_get_fd)rrrr�fileno�szMonitor.filenoNcCs8t|�}|dk	rt|�}|jj|||�|jj|�dS)a
        Filter incoming events.

        ``subsystem`` is a byte or unicode string with the name of a
        subsystem (e.g. ``'input'``).  Only events originating from the
        given subsystem pass the filter and are handed to the caller.

        If given, ``device_type`` is a byte or unicode string specifying the
        device type.  Only devices with the given device type are propagated
        to the caller.  If ``device_type`` is not given, no additional
        filter for a specific device type is installed.

        These filters are executed inside the kernel, and client processes
        will usually not be woken up for device, that do not match these
        filters.

        .. versionchanged:: 0.15
           This method can also be after :meth:`start()` now.
        N)r
rZ/udev_monitor_filter_add_match_subsystem_devtype�udev_monitor_filter_update)rZ	subsystemZdevice_typerrr�	filter_by�s
zMonitor.filter_bycCs"|jj|t|��|jj|�dS)aR
        Filter incoming events by the given ``tag``.

        ``tag`` is a byte or unicode string with the name of a tag.  Only
        events for devices which have this tag attached pass the filter and are
        handed to the caller.

        Like with :meth:`filter_by` this filter is also executed inside the
        kernel, so that client processes are usually not woken up for devices
        without the given ``tag``.

        .. udevversion:: 154

        .. versionadded:: 0.9

        .. versionchanged:: 0.15
           This method can also be after :meth:`start()` now.
        N)rZ!udev_monitor_filter_add_match_tagr
r!)r�tagrrr�
filter_by_tag�szMonitor.filter_by_tagcCs|jj|�|jj|�dS)a
        Remove any filters installed with :meth:`filter_by()` or
        :meth:`filter_by_tag()` from this monitor.

        .. warning::

           Up to udev 181 (and possibly even later versions) the underlying
           ``udev_monitor_filter_remove()`` seems to be broken.  If used with
           affected versions this method always raises
           :exc:`~exceptions.ValueError`.

        Raise :exc:`~exceptions.EnvironmentError` if removal of installed
        filters failed.

        .. versionadded:: 0.15
        N)rZudev_monitor_filter_remover!)rrrr�
remove_filter�szMonitor.remove_filtercCs ddl}|jdt�|j�dS)a�
        Switch the monitor into listing mode.

        Connect to the event source and receive incoming events.  Only after
        calling this method, the monitor listens for incoming events.

        .. note::

           This method is implicitly called by :meth:`__iter__`.  You don't
           need to call it explicitly, if you are iterating over the
           monitor.

        .. deprecated:: 0.16
           Will be removed in 1.0. Use :meth:`start()` instead.
        rNz4Will be removed in 1.0. Use Monitor.start() instead.)�warnings�warn�DeprecationWarning�start)rr&rrr�enable_receiving�szMonitor.enable_receivingcCs*|js&|jj|�tj|tj�d|_dS)a�
        Start this monitor.

        The monitor will not receive events until this method is called. This
        method does nothing if called on an already started :class:`Monitor`.

        .. note::

           Typically you don't need to call this method. It is implicitly
           called by :meth:`poll()` and :meth:`__iter__()`.

        .. seealso:: :attr:`started`
        .. versionchanged:: 0.16
           This method does nothing if the :class:`Monitor` was already
           started.
        TN)rrZudev_monitor_enable_receivingrZset_fd_status_flag�os�
O_NONBLOCK)rrrrr)�sz
Monitor.startcCs|jj||�dS)aN
        Set the receive buffer ``size``.

        ``size`` is the requested buffer size in bytes, as integer.

        .. note::

           The CAP_NET_ADMIN capability must be contained in the effective
           capability set of the caller for this method to succeed.  Otherwise
           :exc:`~exceptions.EnvironmentError` will be raised, with ``errno``
           set to :data:`~errno.EPERM`.  Unprivileged processes typically lack
           this capability.  You can check the capabilities of the current
           process with the python-prctl_ module:

           >>> import prctl
           >>> prctl.cap_effective.net_admin

        Raise :exc:`~exceptions.EnvironmentError`, if the buffer size could not
        bet set.

        .. versionadded:: 0.13

        .. _python-prctl: http://packages.python.org/python-prctl
        N)rZ$udev_monitor_set_receive_buffer_size)r�sizerrr�set_receive_buffer_sizeszMonitor.set_receive_buffer_sizecCsvxpy |jj|�}|r t|j|�SdStk
rl}z.|jtjtjfkrJdS|jtjkrZwn�WYdd}~XqXqWdS)z�Receive a single device from the monitor.

        Return the received :class:`Device`, or ``None`` if no device could be
        received.

        N)	rZudev_monitor_receive_devicerrr�errnoZEAGAINZEWOULDBLOCKZEINTR)rZdevice_p�errorrrr�_receive_device szMonitor._receive_devicecCsL|dk	r|dkrt|d�}|j�ttjj|df�j|�rD|j�SdSdS)a�
        Poll for a device event.

        You can use this method together with :func:`iter()` to synchronously
        monitor events in the current thread::

           for device in iter(monitor.poll, None):
               print('{0.action} on {0.device_path}'.format(device))

        Since this method will never return ``None`` if no ``timeout`` is
        specified, this is effectively an endless loop. With
        :func:`functools.partial()` you can also create a loop that only waits
        for a specified time::

           for device in iter(partial(monitor.poll, 3), None):
               print('{0.action} on {0.device_path}'.format(device))

        This loop will only wait three seconds for a new device event. If no
        device event occurred after three seconds, the loop will exit.

        ``timeout`` is a floating point number that specifies a time-out in
        seconds. If omitted or ``None``, this method blocks until a device
        event is available. If ``0``, this method just polls and will never
        block.

        .. note::

           This method implicitly calls :meth:`start()`.

        Return the received :class:`Device`, or ``None`` if a timeout
        occurred. Raise :exc:`~exceptions.EnvironmentError` if event retrieval
        failed.

        .. seealso::

           :attr:`Device.action`
              The action that created this event.

           :attr:`Device.sequence_number`
              The sequence number of this event.

        .. versionadded:: 0.16
        Nri��r)�intr)r	r�Poll�
for_eventsr1)r�timeoutrrrr5s,zMonitor.pollcCs&ddl}|jdt�|j�}|j|fS)a:
        Receive a single device from the monitor.

        .. warning::

           You *must* call :meth:`start()` before calling this method.

        The caller must make sure, that there are events available in the
        event queue.  The call blocks, until a device is available.

        If a device was available, return ``(action, device)``.  ``device``
        is the :class:`Device` object describing the device.  ``action`` is
        a string describing the action.  Usual actions are:

        ``'add'``
          A device has been added (e.g. a USB device was plugged in)
        ``'remove'``
          A device has been removed (e.g. a USB device was unplugged)
        ``'change'``
          Something about the device changed (e.g. a device property)
        ``'online'``
          The device is online now
        ``'offline'``
          The device is offline now

        Raise :exc:`~exceptions.EnvironmentError`, if no device could be
        read.

        .. deprecated:: 0.16
           Will be removed in 1.0. Use :meth:`Monitor.poll()` instead.
        rNz3Will be removed in 1.0. Use Monitor.poll() instead.)r&r'r(r�action)rr&�devicerrr�receive_devicejs
 zMonitor.receive_deviceccsBddl}|jdt�|j�x |j�}|dk	r|j|fVqWdS)a�
        Wait for incoming events and receive them upon arrival.

        This methods implicitly calls :meth:`start()`, and starts polling the
        :meth:`fileno` of this monitor.  If a event comes in, it receives the
        corresponding device and yields it to the caller.

        The returned iterator is endless, and continues receiving devices
        without ever stopping.

        Yields ``(action, device)`` (see :meth:`receive_device` for a
        description).

        .. deprecated:: 0.16
           Will be removed in 1.0. Use an explicit loop over :meth:`poll()`
           instead, or monitor asynchronously with :class:`MonitorObserver`.
        rNzuWill be removed in 1.0. Use an explicit loop over "poll()" instead, or monitor asynchronously with "MonitorObserver".)r&r'r(r)rr7)rr&r8rrr�__iter__�szMonitor.__iter__)r)N)N)�__name__�
__module__�__qualname__�__doc__rr�classmethodr�propertyrr r"r$r%r*r)r.r1rr9r:rrrrr
.s"&



5&r
c@s:eZdZdZd
dd�Zdd�Zdd�Zd	d
�Zdd�ZdS)�MonitorObservera`
    An asynchronous observer for device events.

    This class subclasses :class:`~threading.Thread` class to asynchronously
    observe a :class:`Monitor` in a background thread:

    >>> from pyudev import Context, Monitor, MonitorObserver
    >>> context = Context()
    >>> monitor = Monitor.from_netlink(context)
    >>> monitor.filter_by(subsystem='input')
    >>> def print_device_event(device):
    ...     print('background event {0.action}: {0.device_path}'.format(device))
    >>> observer = MonitorObserver(monitor, callback=print_device_event, name='monitor-observer')
    >>> observer.daemon
    True
    >>> observer.start()

    In the above example, input device events will be printed in background,
    until :meth:`stop()` is called on ``observer``.

    .. note::

       Instances of this class are always created as daemon thread.  If you do
       not want to use daemon threads for monitoring, you need explicitly set
       :attr:`~threading.Thread.daemon` to ``False`` before invoking
       :meth:`~threading.Thread.start()`.

    .. seealso::

       :attr:`Device.action`
          The action that created this event.

       :attr:`Device.sequence_number`
          The sequence number of this event.

    .. versionadded:: 0.14

    .. versionchanged:: 0.15
       :meth:`Monitor.start()` is implicitly called when the thread is started.
    Ncs�|dkr�dkrtd��n|dk	r2�dk	r2td��tj|f|�|�||_d|_d|_�dk	r~ddl}|jdt��fdd�}||_	dS)	a
        Create a new observer for the given ``monitor``.

        ``monitor`` is the :class:`Monitor` to observe. ``callback`` is the
        callable to invoke on events, with the signature ``callback(device)``
        where ``device`` is the :class:`Device` that caused the event.

        .. warning::

           ``callback`` is invoked in the observer thread, hence the observer
           is blocked while callback executes.

        ``args`` and ``kwargs`` are passed unchanged to the constructor of
        :class:`~threading.Thread`.

        .. deprecated:: 0.16
           The ``event_handler`` argument will be removed in 1.0. Use
           the ``callback`` argument instead.
        .. versionchanged:: 0.16
           Add ``callback`` argument.
        Nzcallback missingz$Use either callback or event handlerTrzL"event_handler" argument will be removed in 1.0. Use Monitor.poll() instead.cs�|j|�S)N)r7)�d)�
event_handlerrr�<lambda>�sz*MonitorObserver.__init__.<locals>.<lambda>)
rrrrZdaemon�_stop_eventr&r'r(�	_callback)rrrC�callback�args�kwargsr&r)rCrr�s
zMonitorObserver.__init__cCs"|j�stjj�|_tj|�dS)zStart the observer thread.N)Zis_aliverZPipe�openrErr))rrrrr)�szMonitorObserver.startcCs�|jj�tjj|jdf|jjdf�}x�x�t|j�D]x\}}||jjj�kr\|jjj	�dS||jj�kr�|dkr�t
t|jjdd�}x&t|d�D]}|j|�q�Wq4t
d��q4Wq(WdS)Nr2r)r6zObserved monitor hung up)rr)rr4r5rErr	r �closer�iterrFr)rZnotifierZfile_descriptorZeventZread_devicer8rrr�runs
zMonitorObserver.runc
CsB|jdkrdS|jj�"t|jjjd�|jjj�WdQRXdS)aT
        Send a stop signal to the background thread.

        The background thread will eventually exit, but it may still be running
        when this method returns.  This method is essentially the asynchronous
        equivalent to :meth:`stop()`.

        .. note::

           The underlying :attr:`monitor` is *not* stopped.
        N�)rEZsinkr	�write�flush)rrrr�	send_stops


zMonitorObserver.send_stopcCs.|j�y|j�Wntk
r(YnXdS)a
        Synchronously stop the background thread.

        .. note::

           This method can safely be called from the observer thread. In this
           case it is equivalent to :meth:`send_stop()`.

        Send a stop signal to the backgroud (see :meth:`send_stop`), and waits
        for the background thread to exit (see :meth:`~threading.Thread.join`)
        if the current thread is *not* the observer thread.

        After this method returns in a thread *that is not the observer
        thread*, the ``callback`` is guaranteed to not be invoked again
        anymore.

        .. note::

           The underlying :attr:`monitor` is *not* stopped.

        .. versionchanged:: 0.16
           This method can be called from the observer thread.
        N)rQ�join�RuntimeError)rrrr�stop*s
zMonitorObserver.stop)NN)	r;r<r=r>rr)rMrQrTrrrrrA�s(
(rA)r>Z
__future__rrrrr+r/Z	threadingr�	functoolsrZ
pyudev.devicerZpyudev._utilr	r
Z
pyudev._osrr�objectr
rArrrr�<module>s__pycache__/monitor.cpython-36.opt-1.pyc000064400000046361150351420040014034 0ustar003

u1�W�Q�@s�dZddlmZmZmZmZddlZddlZddlm	Z	ddl
mZddlm
Z
ddlmZddlmZdd	lmZdd
lmZGdd�de�ZGd
d�de	�ZdS)z�
    pyudev.monitor
    ==============

    Monitor implementation.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
�)�print_function�division�unicode_literals�absolute_importN)�Thread)�partial)�Device)�eintr_retry_call)�ensure_byte_string)�pipe)�pollc@s�eZdZdZdd�Zdd�Zed"dd��Zed	d
��Z	dd�Z
d#dd�Zdd�Zdd�Z
dd�Zdd�Zdd�Zdd�Zd$dd�Zdd�Zd d!�Zd
S)%�Monitorat
    A synchronous device event monitor.

    A :class:`Monitor` objects connects to the udev daemon and listens for
    changes to the device list.  A monitor is created by connecting to the
    kernel daemon through netlink (see :meth:`from_netlink`):

    >>> from pyudev import Context, Monitor
    >>> context = Context()
    >>> monitor = Monitor.from_netlink(context)

    Once the monitor is created, you can add a filter using :meth:`filter_by()`
    or :meth:`filter_by_tag()` to drop incoming events in subsystems, which are
    not of interest to the application:

    >>> monitor.filter_by('input')

    When the monitor is eventually set up, you can either poll for events
    synchronously:

    >>> device = monitor.poll(timeout=3)
    >>> if device:
    ...     print('{0.action}: {0}'.format(device))
    ...

    Or you can monitor events asynchronously with :class:`MonitorObserver`.

    To integrate into various event processing frameworks, the monitor provides
    a :func:`selectable <select.select>` file description by :meth:`fileno()`.
    However, do *not*  read or write directly on this file descriptor.

    Instances of this class can directly be given as ``udev_monitor *`` to
    functions wrapped through :mod:`ctypes`.

    .. versionchanged:: 0.16
       Remove :meth:`from_socket()` which is deprecated, and even removed in
       recent udev versions.
    cCs||_||_|j|_d|_dS)NF)�contextZ_as_parameter_�_libudev�_started)�selfrZ	monitor_p�r�/usr/lib/python3.6/monitor.py�__init__VszMonitor.__init__cCs|jj|�dS)N)rZudev_monitor_unref)rrrr�__del__\szMonitor.__del__�udevcCs>|dkrtdj|���|jj|t|��}|s4td��|||�S)a�
        Create a monitor by connecting to the kernel daemon through netlink.

        ``context`` is the :class:`Context` to use.  ``source`` is a string,
        describing the event source.  Two sources are available:

        ``'udev'`` (the default)
          Events emitted after udev as registered and configured the device.
          This is the absolutely recommended source for applications.

        ``'kernel'``
          Events emitted directly after the kernel has seen the device.  The
          device has not yet been configured by udev and might not be usable
          at all.  **Never** use this, unless you know what you are doing.

        Return a new :class:`Monitor` object, which is connected to the
        given source.  Raise :exc:`~exceptions.ValueError`, if an invalid
        source has been specified.  Raise
        :exc:`~exceptions.EnvironmentError`, if the creation of the monitor
        failed.
        �kernelrz8Invalid source: {0!r}. Must be one of "udev" or "kernel"zCould not create udev monitor)rr)�
ValueError�formatrZudev_monitor_new_from_netlinkr
�EnvironmentError)�clsr�source�monitorrrr�from_netlink_szMonitor.from_netlinkcCs|jS)z�
        ``True``, if this monitor was started, ``False`` otherwise. Readonly.

        .. seealso:: :meth:`start()`
        .. versionadded:: 0.16
        )r)rrrr�startedszMonitor.startedcCs|jj|�S)z�
        Return the file description associated with this monitor as integer.

        This is really a real file descriptor ;), which can be watched and
        :func:`select.select`\ ed.
        )rZudev_monitor_get_fd)rrrr�fileno�szMonitor.filenoNcCs8t|�}|dk	rt|�}|jj|||�|jj|�dS)a
        Filter incoming events.

        ``subsystem`` is a byte or unicode string with the name of a
        subsystem (e.g. ``'input'``).  Only events originating from the
        given subsystem pass the filter and are handed to the caller.

        If given, ``device_type`` is a byte or unicode string specifying the
        device type.  Only devices with the given device type are propagated
        to the caller.  If ``device_type`` is not given, no additional
        filter for a specific device type is installed.

        These filters are executed inside the kernel, and client processes
        will usually not be woken up for device, that do not match these
        filters.

        .. versionchanged:: 0.15
           This method can also be after :meth:`start()` now.
        N)r
rZ/udev_monitor_filter_add_match_subsystem_devtype�udev_monitor_filter_update)rZ	subsystemZdevice_typerrr�	filter_by�s
zMonitor.filter_bycCs"|jj|t|��|jj|�dS)aR
        Filter incoming events by the given ``tag``.

        ``tag`` is a byte or unicode string with the name of a tag.  Only
        events for devices which have this tag attached pass the filter and are
        handed to the caller.

        Like with :meth:`filter_by` this filter is also executed inside the
        kernel, so that client processes are usually not woken up for devices
        without the given ``tag``.

        .. udevversion:: 154

        .. versionadded:: 0.9

        .. versionchanged:: 0.15
           This method can also be after :meth:`start()` now.
        N)rZ!udev_monitor_filter_add_match_tagr
r!)r�tagrrr�
filter_by_tag�szMonitor.filter_by_tagcCs|jj|�|jj|�dS)a
        Remove any filters installed with :meth:`filter_by()` or
        :meth:`filter_by_tag()` from this monitor.

        .. warning::

           Up to udev 181 (and possibly even later versions) the underlying
           ``udev_monitor_filter_remove()`` seems to be broken.  If used with
           affected versions this method always raises
           :exc:`~exceptions.ValueError`.

        Raise :exc:`~exceptions.EnvironmentError` if removal of installed
        filters failed.

        .. versionadded:: 0.15
        N)rZudev_monitor_filter_remover!)rrrr�
remove_filter�szMonitor.remove_filtercCs ddl}|jdt�|j�dS)a�
        Switch the monitor into listing mode.

        Connect to the event source and receive incoming events.  Only after
        calling this method, the monitor listens for incoming events.

        .. note::

           This method is implicitly called by :meth:`__iter__`.  You don't
           need to call it explicitly, if you are iterating over the
           monitor.

        .. deprecated:: 0.16
           Will be removed in 1.0. Use :meth:`start()` instead.
        rNz4Will be removed in 1.0. Use Monitor.start() instead.)�warnings�warn�DeprecationWarning�start)rr&rrr�enable_receiving�szMonitor.enable_receivingcCs*|js&|jj|�tj|tj�d|_dS)a�
        Start this monitor.

        The monitor will not receive events until this method is called. This
        method does nothing if called on an already started :class:`Monitor`.

        .. note::

           Typically you don't need to call this method. It is implicitly
           called by :meth:`poll()` and :meth:`__iter__()`.

        .. seealso:: :attr:`started`
        .. versionchanged:: 0.16
           This method does nothing if the :class:`Monitor` was already
           started.
        TN)rrZudev_monitor_enable_receivingrZset_fd_status_flag�os�
O_NONBLOCK)rrrrr)�sz
Monitor.startcCs|jj||�dS)aN
        Set the receive buffer ``size``.

        ``size`` is the requested buffer size in bytes, as integer.

        .. note::

           The CAP_NET_ADMIN capability must be contained in the effective
           capability set of the caller for this method to succeed.  Otherwise
           :exc:`~exceptions.EnvironmentError` will be raised, with ``errno``
           set to :data:`~errno.EPERM`.  Unprivileged processes typically lack
           this capability.  You can check the capabilities of the current
           process with the python-prctl_ module:

           >>> import prctl
           >>> prctl.cap_effective.net_admin

        Raise :exc:`~exceptions.EnvironmentError`, if the buffer size could not
        bet set.

        .. versionadded:: 0.13

        .. _python-prctl: http://packages.python.org/python-prctl
        N)rZ$udev_monitor_set_receive_buffer_size)r�sizerrr�set_receive_buffer_sizeszMonitor.set_receive_buffer_sizecCsvxpy |jj|�}|r t|j|�SdStk
rl}z.|jtjtjfkrJdS|jtjkrZwn�WYdd}~XqXqWdS)z�Receive a single device from the monitor.

        Return the received :class:`Device`, or ``None`` if no device could be
        received.

        N)	rZudev_monitor_receive_devicerrr�errnoZEAGAINZEWOULDBLOCKZEINTR)rZdevice_p�errorrrr�_receive_device szMonitor._receive_devicecCsL|dk	r|dkrt|d�}|j�ttjj|df�j|�rD|j�SdSdS)a�
        Poll for a device event.

        You can use this method together with :func:`iter()` to synchronously
        monitor events in the current thread::

           for device in iter(monitor.poll, None):
               print('{0.action} on {0.device_path}'.format(device))

        Since this method will never return ``None`` if no ``timeout`` is
        specified, this is effectively an endless loop. With
        :func:`functools.partial()` you can also create a loop that only waits
        for a specified time::

           for device in iter(partial(monitor.poll, 3), None):
               print('{0.action} on {0.device_path}'.format(device))

        This loop will only wait three seconds for a new device event. If no
        device event occurred after three seconds, the loop will exit.

        ``timeout`` is a floating point number that specifies a time-out in
        seconds. If omitted or ``None``, this method blocks until a device
        event is available. If ``0``, this method just polls and will never
        block.

        .. note::

           This method implicitly calls :meth:`start()`.

        Return the received :class:`Device`, or ``None`` if a timeout
        occurred. Raise :exc:`~exceptions.EnvironmentError` if event retrieval
        failed.

        .. seealso::

           :attr:`Device.action`
              The action that created this event.

           :attr:`Device.sequence_number`
              The sequence number of this event.

        .. versionadded:: 0.16
        Nri��r)�intr)r	r�Poll�
for_eventsr1)r�timeoutrrrr5s,zMonitor.pollcCs&ddl}|jdt�|j�}|j|fS)a:
        Receive a single device from the monitor.

        .. warning::

           You *must* call :meth:`start()` before calling this method.

        The caller must make sure, that there are events available in the
        event queue.  The call blocks, until a device is available.

        If a device was available, return ``(action, device)``.  ``device``
        is the :class:`Device` object describing the device.  ``action`` is
        a string describing the action.  Usual actions are:

        ``'add'``
          A device has been added (e.g. a USB device was plugged in)
        ``'remove'``
          A device has been removed (e.g. a USB device was unplugged)
        ``'change'``
          Something about the device changed (e.g. a device property)
        ``'online'``
          The device is online now
        ``'offline'``
          The device is offline now

        Raise :exc:`~exceptions.EnvironmentError`, if no device could be
        read.

        .. deprecated:: 0.16
           Will be removed in 1.0. Use :meth:`Monitor.poll()` instead.
        rNz3Will be removed in 1.0. Use Monitor.poll() instead.)r&r'r(r�action)rr&�devicerrr�receive_devicejs
 zMonitor.receive_deviceccsBddl}|jdt�|j�x |j�}|dk	r|j|fVqWdS)a�
        Wait for incoming events and receive them upon arrival.

        This methods implicitly calls :meth:`start()`, and starts polling the
        :meth:`fileno` of this monitor.  If a event comes in, it receives the
        corresponding device and yields it to the caller.

        The returned iterator is endless, and continues receiving devices
        without ever stopping.

        Yields ``(action, device)`` (see :meth:`receive_device` for a
        description).

        .. deprecated:: 0.16
           Will be removed in 1.0. Use an explicit loop over :meth:`poll()`
           instead, or monitor asynchronously with :class:`MonitorObserver`.
        rNzuWill be removed in 1.0. Use an explicit loop over "poll()" instead, or monitor asynchronously with "MonitorObserver".)r&r'r(r)rr7)rr&r8rrr�__iter__�szMonitor.__iter__)r)N)N)�__name__�
__module__�__qualname__�__doc__rr�classmethodr�propertyrr r"r$r%r*r)r.r1rr9r:rrrrr
.s"&



5&r
c@s:eZdZdZd
dd�Zdd�Zdd�Zd	d
�Zdd�ZdS)�MonitorObservera`
    An asynchronous observer for device events.

    This class subclasses :class:`~threading.Thread` class to asynchronously
    observe a :class:`Monitor` in a background thread:

    >>> from pyudev import Context, Monitor, MonitorObserver
    >>> context = Context()
    >>> monitor = Monitor.from_netlink(context)
    >>> monitor.filter_by(subsystem='input')
    >>> def print_device_event(device):
    ...     print('background event {0.action}: {0.device_path}'.format(device))
    >>> observer = MonitorObserver(monitor, callback=print_device_event, name='monitor-observer')
    >>> observer.daemon
    True
    >>> observer.start()

    In the above example, input device events will be printed in background,
    until :meth:`stop()` is called on ``observer``.

    .. note::

       Instances of this class are always created as daemon thread.  If you do
       not want to use daemon threads for monitoring, you need explicitly set
       :attr:`~threading.Thread.daemon` to ``False`` before invoking
       :meth:`~threading.Thread.start()`.

    .. seealso::

       :attr:`Device.action`
          The action that created this event.

       :attr:`Device.sequence_number`
          The sequence number of this event.

    .. versionadded:: 0.14

    .. versionchanged:: 0.15
       :meth:`Monitor.start()` is implicitly called when the thread is started.
    Ncs�|dkr�dkrtd��n|dk	r2�dk	r2td��tj|f|�|�||_d|_d|_�dk	r~ddl}|jdt��fdd�}||_	dS)	a
        Create a new observer for the given ``monitor``.

        ``monitor`` is the :class:`Monitor` to observe. ``callback`` is the
        callable to invoke on events, with the signature ``callback(device)``
        where ``device`` is the :class:`Device` that caused the event.

        .. warning::

           ``callback`` is invoked in the observer thread, hence the observer
           is blocked while callback executes.

        ``args`` and ``kwargs`` are passed unchanged to the constructor of
        :class:`~threading.Thread`.

        .. deprecated:: 0.16
           The ``event_handler`` argument will be removed in 1.0. Use
           the ``callback`` argument instead.
        .. versionchanged:: 0.16
           Add ``callback`` argument.
        Nzcallback missingz$Use either callback or event handlerTrzL"event_handler" argument will be removed in 1.0. Use Monitor.poll() instead.cs�|j|�S)N)r7)�d)�
event_handlerrr�<lambda>�sz*MonitorObserver.__init__.<locals>.<lambda>)
rrrrZdaemon�_stop_eventr&r'r(�	_callback)rrrC�callback�args�kwargsr&r)rCrr�s
zMonitorObserver.__init__cCs"|j�stjj�|_tj|�dS)zStart the observer thread.N)Zis_aliverZPipe�openrErr))rrrrr)�szMonitorObserver.startcCs�|jj�tjj|jdf|jjdf�}x�x�t|j�D]x\}}||jjj�kr\|jjj	�dS||jj�kr�|dkr�t
t|jjdd�}x&t|d�D]}|j|�q�Wq4t
d��q4Wq(WdS)Nr2r)r6zObserved monitor hung up)rr)rr4r5rErr	r �closer�iterrFr)rZnotifierZfile_descriptorZeventZread_devicer8rrr�runs
zMonitorObserver.runc
CsB|jdkrdS|jj�"t|jjjd�|jjj�WdQRXdS)aT
        Send a stop signal to the background thread.

        The background thread will eventually exit, but it may still be running
        when this method returns.  This method is essentially the asynchronous
        equivalent to :meth:`stop()`.

        .. note::

           The underlying :attr:`monitor` is *not* stopped.
        N�)rEZsinkr	�write�flush)rrrr�	send_stops


zMonitorObserver.send_stopcCs.|j�y|j�Wntk
r(YnXdS)a
        Synchronously stop the background thread.

        .. note::

           This method can safely be called from the observer thread. In this
           case it is equivalent to :meth:`send_stop()`.

        Send a stop signal to the backgroud (see :meth:`send_stop`), and waits
        for the background thread to exit (see :meth:`~threading.Thread.join`)
        if the current thread is *not* the observer thread.

        After this method returns in a thread *that is not the observer
        thread*, the ``callback`` is guaranteed to not be invoked again
        anymore.

        .. note::

           The underlying :attr:`monitor` is *not* stopped.

        .. versionchanged:: 0.16
           This method can be called from the observer thread.
        N)rQ�join�RuntimeError)rrrr�stop*s
zMonitorObserver.stop)NN)	r;r<r=r>rr)rMrQrTrrrrrA�s(
(rA)r>Z
__future__rrrrr+r/Z	threadingr�	functoolsrZ
pyudev.devicerZpyudev._utilr	r
Z
pyudev._osrr�objectr
rArrrr�<module>s__pycache__/core.cpython-36.opt-1.pyc000064400000031216150351420040013266 0ustar003

u1�Ws4�@s�dZddlmZmZmZmZddlmZddlm	Z	ddl
mZddl
mZddl
mZddlmZdd	lmZdd
lmZddlmZGdd
�d
e�ZGdd�de�ZdS)z�
    pyudev.core
    ===========

    Core types and functions of :mod:`pyudev`.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
�)�print_function�division�unicode_literals�absolute_import)�Devices)�DeviceNotFoundAtPathError)�ERROR_CHECKERS)�
SIGNATURES)�load_ctypes_library)�ensure_byte_string)�ensure_unicode_string)�property_value_to_bytes)�udev_list_iteratec@sfeZdZdZdd�Zdd�Zedd��Zedd	��Zed
d��Z	edd
��Z
e
jdd
��Z
dd�ZdS)�Contexta
    A device database connection.

    This class represents a connection to the udev device database, and is
    really *the* central object to access udev.  You need an instance of this
    class for almost anything else in pyudev.

    This class itself gives access to various udev configuration data (e.g.
    :attr:`sys_path`, :attr:`device_path`), and provides device enumeration
    (:meth:`list_devices()`).

    Instances of this class can directly be given as ``udev *`` to functions
    wrapped through :mod:`ctypes`.
    cCstdtt�|_|jj�|_dS)z'
        Create a new context.
        ZudevN)r
r	r�_libudevZudev_new�_as_parameter_)�self�r�/usr/lib/python3.6/core.py�__init__<szContext.__init__cCs|jj|�dS)N)rZ
udev_unref)rrrr�__del__CszContext.__del__cCs$t|jd�rt|jj|��SdSdS)zV
        The ``sysfs`` mount point defaulting to ``/sys'`` as unicode string.
        �udev_get_sys_pathz/sysN)�hasattrrrr)rrrr�sys_pathFszContext.sys_pathcCs$t|jd�rt|jj|��SdSdS)zU
        The device directory path defaulting to ``/dev`` as unicode string.
        �udev_get_dev_pathz/devN)rrrr)rrrr�device_pathQszContext.device_pathcCs$t|jd�rt|jj|��SdSdS)z�
        The run runtime directory path defaulting to ``/run`` as unicode
        string.

        .. udevversion:: 167

        .. versionadded:: 0.10
        �udev_get_run_pathz	/run/udevN)rrrr)rrrr�run_path\s
zContext.run_pathcCs|jj|�S)a
        The logging priority of the interal logging facitility of udev as
        integer with a standard :mod:`syslog` priority.  Assign to this
        property to change the logging priority.

        UDev uses the standard :mod:`syslog` priorities.  Constants for these
        priorities are defined in the :mod:`syslog` module in the standard
        library:

        >>> import syslog
        >>> context = pyudev.Context()
        >>> context.log_priority = syslog.LOG_DEBUG

        .. versionadded:: 0.9
        )rZudev_get_log_priority)rrrr�log_prioritykszContext.log_prioritycCs|jj||�dS)zT
        Set the log priority.

        :param int value: the log priority.
        N)rZudev_set_log_priority)r�valuerrrr~scKst|�jf|�S)a"
        List all available devices.

        The arguments of this method are the same as for
        :meth:`Enumerator.match()`.  In fact, the arguments are simply passed
        straight to method :meth:`~Enumerator.match()`.

        This function creates and returns an :class:`Enumerator` object,
        that can be used to filter the list of devices, and eventually
        retrieve :class:`Device` objects representing matching devices.

        .. versionchanged:: 0.8
           Accept keyword arguments now for easy matching.
        )�
Enumerator�match)r�kwargsrrr�list_devices�szContext.list_devicesN)
�__name__�
__module__�__qualname__�__doc__rr�propertyrrrr�setterr#rrrrr,s	rc@sleZdZdZdd�Zdd�Zdd�Zdd	d
�Zdd�Zd
d�Z	ddd�Z
dd�Zdd�Zdd�Z
dd�ZdS)r a�
    A filtered iterable of devices.

    To retrieve devices, simply iterate over an instance of this class.
    This operation yields :class:`Device` objects representing the available
    devices.

    Before iteration the device list can be filtered by subsystem or by
    property values using :meth:`match_subsystem` and
    :meth:`match_property`.  Multiple subsystem (property) filters are
    combined using a logical OR, filters of different types are combined
    using a logical AND.  The following filter for instance::

        devices.match_subsystem('block').match_property(
            'ID_TYPE', 'disk').match_property('DEVTYPE', 'disk')

    means the following::

        subsystem == 'block' and (ID_TYPE == 'disk' or DEVTYPE == 'disk')

    Once added, a filter cannot be removed anymore.  Create a new object
    instead.

    Instances of this class can directly be given as given ``udev_enumerate *``
    to functions wrapped through :mod:`ctypes`.
    cCs2t|t�std��||_|jj|�|_|j|_dS)z�
        Create a new enumerator with the given ``context`` (a
        :class:`Context` instance).

        While you can create objects of this class directly, this is not
        recommended.  Call :method:`Context.list_devices()` instead.
        zInvalid context objectN)�
isinstancer�	TypeError�contextrZudev_enumerate_newr)rr,rrrr�s

zEnumerator.__init__cCs|jj|�dS)N)rZudev_enumerate_unref)rrrrr�szEnumerator.__del__cKs�|jdd�}|dk	r|j|�|jdd�}|dk	r<|j|�|jdd�}|dk	rZ|j|�|jdd�}|dk	rx|j|�x |j�D]\}}|j||�q�W|S)a2
        Include devices according to the rules defined by the keyword
        arguments.  These keyword arguments are interpreted as follows:

        - The value for the keyword argument ``subsystem`` is forwarded to
          :meth:`match_subsystem()`.
        - The value for the keyword argument ``sys_name`` is forwared to
          :meth:`match_sys_name()`.
        - The value for the keyword argument ``tag`` is forwared to
          :meth:`match_tag()`.
        - The value for the keyword argument ``parent`` is forwared to
          :meth:`match_parent()`.
        - All other keyword arguments are forwareded one by one to
          :meth:`match_property()`.  The keyword argument itself is interpreted
          as property name, the value of the keyword argument as the property
          value.

        All keyword arguments are optional, calling this method without no
        arguments at all is simply a noop.

        Return the instance again.

        .. versionadded:: 0.8

        .. versionchanged:: 0.13
           Add ``parent`` keyword.
        �	subsystemN�sys_name�tag�parent)�pop�match_subsystem�match_sys_name�	match_tag�match_parent�items�match_property)rr"r-r.r/r0�proprrrrr!�s



zEnumerator.matchFcCs&|r|jjn|jj}||t|��|S)a$
        Include all devices, which are part of the given ``subsystem``.

        ``subsystem`` is either a unicode string or a byte string, containing
        the name of the subsystem.  If ``nomatch`` is ``True`` (default is
        ``False``), the match is inverted:  A device is only included if it is
        *not* part of the given ``subsystem``.

        Note that, if a device has no subsystem, it is not included either
        with value of ``nomatch`` True or with value of ``nomatch`` False.

        Return the instance again.
        )rZ$udev_enumerate_add_nomatch_subsystemZ"udev_enumerate_add_match_subsystemr)rr-�nomatchr!rrrr2�szEnumerator.match_subsystemcCs|jj|t|��|S)z�
        Include all devices with the given name.

        ``sys_name`` is a byte or unicode string containing the device name.

        Return the instance again.

        .. versionadded:: 0.8
        )rZ udev_enumerate_add_match_sysnamer)rr.rrrr3s
zEnumerator.match_sys_namecCs|jj|t|�t|��|S)a�
        Include all devices, whose ``prop`` has the given ``value``.

        ``prop`` is either a unicode string or a byte string, containing
        the name of the property to match.  ``value`` is a property value,
        being one of the following types:

        - :func:`int`
        - :func:`bool`
        - A byte string
        - Anything convertable to a unicode string (including a unicode string
          itself)

        Return the instance again.
        )rZ!udev_enumerate_add_match_propertyrr
)rr8rrrrr7szEnumerator.match_propertycCs,|s|jjn|jj}||t|�t|��|S)a�
        Include all devices, whose ``attribute`` has the given ``value``.

        ``attribute`` is either a unicode string or a byte string, containing
        the name of a sys attribute to match.  ``value`` is an attribute value,
        being one of the following types:

        - :func:`int`,
        - :func:`bool`
        - A byte string
        - Anything convertable to a unicode string (including a unicode string
          itself)

        If ``nomatch`` is ``True`` (default is ``False``), the match is
        inverted:  A device is include if the ``attribute`` does *not* match
        the given ``value``.

        .. note::

           If ``nomatch`` is ``True``, devices which do not have the given
           ``attribute`` at all are also included.  In other words, with
           ``nomatch=True`` the given ``attribute`` is *not* guaranteed to
           exist on all returned devices.

        Return the instance again.
        )rZ udev_enumerate_add_match_sysattrZ"udev_enumerate_add_nomatch_sysattrrr
)rZ	attributerr9r!rrr�match_attribute's


zEnumerator.match_attributecCs|jj|t|��|S)z�
        Include all devices, which have the given ``tag`` attached.

        ``tag`` is a byte or unicode string containing the tag name.

        Return the instance again.

        .. udevversion:: 154

        .. versionadded:: 0.6
        )rZudev_enumerate_add_match_tagr)rr/rrrr4IszEnumerator.match_tagcCs|jj|�|S)a�
        Include only devices, which are initialized.

        Initialized devices have properly set device node permissions and
        context, and are (in case of network devices) fully renamed.

        Currently this will not affect devices which do not have device nodes
        and are not network interfaces.

        Return the instance again.

        .. seealso:: :attr:`Device.is_initialized`

        .. udevversion:: 165

        .. versionadded:: 0.8
        )rZ'udev_enumerate_add_match_is_initialized)rrrr�match_is_initializedXszEnumerator.match_is_initializedcCs|jj||�|S)a 
        Include all devices on the subtree of the given ``parent`` device.

        The ``parent`` device itself is also included.

        ``parent`` is a :class:`~pyudev.Device`.

        Return the instance again.

        .. udevversion:: 172

        .. versionadded:: 0.13
        )rZudev_enumerate_add_match_parent)rr0rrrr5mszEnumerator.match_parentccsb|jj|�|jj|�}xDt|j|�D]4\}}ytj|j|�VWq&tk
rXw&Yq&Xq&WdS)z\
        Iterate over all matching devices.

        Yield :class:`Device` objects.
        N)rZudev_enumerate_scan_devicesZudev_enumerate_get_list_entryrrZ
from_sys_pathr,r)r�entry�name�_rrr�__iter__~szEnumerator.__iter__N)F)F)r$r%r&r'rrr!r2r3r7r:r4r;r5r?rrrrr �s,

"r N)r'Z
__future__rrrrZ
pyudev.devicerZpyudev.device._errorsrZpyudev._ctypeslib.libudevrr	Zpyudev._ctypeslib.utilsr
Zpyudev._utilrrr
r�objectrr rrrr�<module>sm__pycache__/_qt_base.cpython-36.opt-1.pyc000064400000014331150351420040014112 0ustar003

u1�Wk�@s�dZddlmZddlmZddlmZddlmZddlZddlmZGdd	�d	e	�Z
Gd
d�de
�Zdd
�ZGdd�de	�Z
Gdd�de	�ZdS)z�
    pyudev._qt_base
    ===============

    Base mixin class for Qt4,Qt5 support.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
�)�absolute_import)�division)�print_function)�unicode_literalsN)�Devicec@sBeZdZdZdd�Zedd��Zejdd��Zdd�Zd	d
�Z	dS)�MonitorObserverMixinz0
    Base mixin for pyqt monitor observers.
    cCs2||_||j�|j|�|_|jjtj|j�dS)N)�monitor�filenoZRead�notifierZ	activated�intZconnect�_process_udev_event)�selfr�notifier_class�r�/usr/lib/python3.6/_qt_base.py�_setup_notifier+sz$MonitorObserverMixin._setup_notifiercCs
|jj�S)aY
        Whether this observer is enabled or not.

        If ``True`` (the default), this observer is enabled, and emits events.
        Otherwise it is disabled and does not emit any events.  This merely
        reflects the state of the ``enabled`` property of the underlying
        :attr:`notifier`.

        .. versionadded:: 0.14
        )r
Z	isEnabled)r
rrr�enabled1szMonitorObserverMixin.enabledcCs|jj|�dS)N)r
Z
setEnabled)r
�valuerrrr?scCs$|jjdd�}|dk	r |j|�dS)z�
        Attempt to receive a single device event from the monitor, process
        the event and emit corresponding signals.

        Called by ``QSocketNotifier``, if data is available on the udev
        monitoring socket.
        r)ZtimeoutN)rZpoll�_emit_event)r
�devicerrrrCsz(MonitorObserverMixin._process_udev_eventcCs|jj|�dS)N)�deviceEvent�emit)r
rrrrrOsz MonitorObserverMixin._emit_eventN)
�__name__�
__module__�__qualname__�__doc__r�propertyr�setterrrrrrrr%src@s eZdZdZdd�Zdd�ZdS)�QUDevMonitorObserverMixinz*
    Obsolete monitor observer mixin.
    cCs>tj|||�|j|j|j|jd�|_ddl}|jdt	�dS)N)�add�removeZchangeZmoverzAWill be removed in 1.0. Use pyudev.pyqt4.MonitorObserver instead.)
rr�deviceAdded�
deviceRemoved�
deviceChanged�deviceMoved�_action_signal_map�warnings�warn�DeprecationWarning)r
rrr&rrrrYsz)QUDevMonitorObserverMixin._setup_notifiercCs4|jj|j|�|jj|j�}|dk	r0|j|�dS)N)rr�actionr%�get)r
r�signalrrrrdsz%QUDevMonitorObserverMixin._emit_eventN)rrrrrrrrrrrSsrcsd��fdd�	}|S)a
    Generates an initializer to observer the given ``monitor``
    (a :class:`~pyudev.Monitor`):

    ``parent`` is the parent :class:`~PyQt{4,5}.QtCore.QObject` of this
    object.  It is passed unchanged to the inherited constructor of
    :class:`~PyQt{4,5}.QtCore.QObject`.
    Ncs�j||�|j|��dS)N)�__init__r)r
r�parent)�qobject�socket_notifierrrr,tszmake_init.<locals>.__init__)Nr)r.r/r,r)r.r/r�	make_initjs
r0c@seZdZdZedd��ZdS)�MonitorObserverGeneratorz4
    Class to generate a MonitorObserver class.
    cCs.ttd�|tftd�t||�td�|t�i�S)aGenerates an observer for device events integrating into the
        PyQt{4,5} mainloop.

        This class inherits :class:`~PyQt{4,5}.QtCore.QObject` to turn device
        events into Qt signals:

        >>> from pyudev import Context, Monitor
        >>> from pyudev.pyqt4 import MonitorObserver
        >>> context = Context()
        >>> monitor = Monitor.from_netlink(context)
        >>> monitor.filter_by(subsystem='input')
        >>> observer = MonitorObserver(monitor)
        >>> def device_event(device):
        ...     print('event {0} on device {1}'.format(device.action, device))
        >>> observer.deviceEvent.connect(device_event)
        >>> monitor.start()

        This class is a child of :class:`~{PySide, PyQt{4,5}}.QtCore.QObject`.

        ZMonitorObserverr,r)�type�strrr0r)r.r+r/rrr�make_monitor_observer�s
z.MonitorObserverGenerator.make_monitor_observerN)rrrr�staticmethodr4rrrrr1|sr1c@seZdZdZedd��ZdS)�QUDevMonitorObserverGeneratorz4
    Class to generate a MonitorObserver class.
    cCsbttd�|tftd�t||�td�|tjt�td�|t�td�|t�td�|t�td�|t�i�S)aGenerates an observer for device events integrating into the
        PyQt{4,5} mainloop.

        This class inherits :class:`~PyQt{4,5}.QtCore.QObject` to turn device
        events into Qt signals:

        >>> from pyudev import Context, Monitor
        >>> from pyudev.pyqt4 import MonitorObserver
        >>> context = Context()
        >>> monitor = Monitor.from_netlink(context)
        >>> monitor.filter_by(subsystem='input')
        >>> observer = MonitorObserver(monitor)
        >>> def device_event(device):
        ...     print('event {0} on device {1}'.format(device.action, device))
        >>> observer.deviceEvent.connect(device_event)
        >>> monitor.start()

        This class is a child of :class:`~{PyQt{4,5}, PySide}.QtCore.QObject`.

        ZQUDevMonitorObserverr,rr!r"r#r$)r2r3rr0�sixZ	text_typer)r.r+r/rrrr4�sz3QUDevMonitorObserverGenerator.make_monitor_observerN)rrrrr5r4rrrrr6�sr6)rZ
__future__rrrrr7Z
pyudev.devicer�objectrrr0r1r6rrrr�<module>s.'__pycache__/_compat.cpython-36.opt-1.pyc000064400000001476150351420040013765 0ustar003

װV��@s<dZddlmZmZmZmZddlmZmZm	Z	dd�Z
dS)z�
    pyudev._compat
    ==============

    Compatibility for Python versions, that lack certain functions.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
�)�print_function�division�unicode_literals�absolute_import)�Popen�CalledProcessError�PIPEcCs2t|td�}|j�d}|jdkr.t|j|��|S)z]
    Compatibility with :func:`subprocess.check_output` from Python 2.7 and
    upwards.
    )�stdoutr)rrZcommunicate�
returncoder)Zcommand�proc�output�r
�/usr/lib/python3.6/_compat.py�check_output#s

rN)�__doc__Z
__future__rrrr�
subprocessrrrrr
r
r
r�<module>s__pycache__/_compat.cpython-36.pyc000064400000001476150351420040013026 0ustar003

װV��@s<dZddlmZmZmZmZddlmZmZm	Z	dd�Z
dS)z�
    pyudev._compat
    ==============

    Compatibility for Python versions, that lack certain functions.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
�)�print_function�division�unicode_literals�absolute_import)�Popen�CalledProcessError�PIPEcCs2t|td�}|j�d}|jdkr.t|j|��|S)z]
    Compatibility with :func:`subprocess.check_output` from Python 2.7 and
    upwards.
    )�stdoutr)rrZcommunicate�
returncoder)Zcommand�proc�output�r
�/usr/lib/python3.6/_compat.py�check_output#s

rN)�__doc__Z
__future__rrrr�
subprocessrrrrr
r
r
r�<module>s__pycache__/__init__.cpython-36.pyc000064400000003402150351420040013132 0ustar003

N�#W�	�@s@dZddlmZddlmZddlmZddlmZddlmZddlmZddlm	Z	dd	lm
Z
dd
lmZddlmZddlm
Z
dd
lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddl m!Z!dS)a.
    pyudev
    ======

    A binding to libudev.

    The :class:`Context` provides the connection to the udev device database
    and enumerates devices.  Individual devices are represented by the
    :class:`Device` class.

    Device monitoring is provided by :class:`Monitor` and
    :class:`MonitorObserver`.  With :mod:`pyudev.pyqt4`, :mod:`pyudev.pyside`,
    :mod:`pyudev.glib` and :mod:`pyudev.wx` device monitoring can be integrated
    into the event loop of various GUI toolkits.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
�)�absolute_import)�division)�print_function)�unicode_literals)�
Attributes)�Device)�Devices)�DeviceNotFoundAtPathError)�DeviceNotFoundByFileError)�DeviceNotFoundByNameError)�DeviceNotFoundByNumberError)�DeviceNotFoundError)� DeviceNotFoundInEnvironmentError)�Tags)�DeviceFileHypothesis)�DeviceNameHypothesis)�DeviceNumberHypothesis)�DevicePathHypothesis)�	Discovery)�Context)�
Enumerator)�Monitor)�MonitorObserver)�__version__)�__version_info__)�udev_versionN)"�__doc__Z
__future__rrrrZ
pyudev.devicerrrr	r
rrr
rrZpyudev.discoverrrrrrZpyudev.corerrZpyudev.monitorrrZpyudev.versionrrZpyudev._utilr�rr�/usr/lib/python3.6/__init__.py�<module>#s4__pycache__/__init__.cpython-36.opt-1.pyc000064400000003402150351420040014071 0ustar003

N�#W�	�@s@dZddlmZddlmZddlmZddlmZddlmZddlmZddlm	Z	dd	lm
Z
dd
lmZddlmZddlm
Z
dd
lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddl m!Z!dS)a.
    pyudev
    ======

    A binding to libudev.

    The :class:`Context` provides the connection to the udev device database
    and enumerates devices.  Individual devices are represented by the
    :class:`Device` class.

    Device monitoring is provided by :class:`Monitor` and
    :class:`MonitorObserver`.  With :mod:`pyudev.pyqt4`, :mod:`pyudev.pyside`,
    :mod:`pyudev.glib` and :mod:`pyudev.wx` device monitoring can be integrated
    into the event loop of various GUI toolkits.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
�)�absolute_import)�division)�print_function)�unicode_literals)�
Attributes)�Device)�Devices)�DeviceNotFoundAtPathError)�DeviceNotFoundByFileError)�DeviceNotFoundByNameError)�DeviceNotFoundByNumberError)�DeviceNotFoundError)� DeviceNotFoundInEnvironmentError)�Tags)�DeviceFileHypothesis)�DeviceNameHypothesis)�DeviceNumberHypothesis)�DevicePathHypothesis)�	Discovery)�Context)�
Enumerator)�Monitor)�MonitorObserver)�__version__)�__version_info__)�udev_versionN)"�__doc__Z
__future__rrrrZ
pyudev.devicerrrr	r
rrr
rrZpyudev.discoverrrrrrZpyudev.corerrZpyudev.monitorrrZpyudev.versionrrZpyudev._utilr�rr�/usr/lib/python3.6/__init__.py�<module>#s4__pycache__/_util.cpython-36.pyc000064400000013502150351420040012511 0ustar003

N�#W(�@s�dZddlmZmZmZmZyddlmZWn ek
rLddl	mZYnXddl
Z
ddlZddlZddl
Z
ddlZdd�Zdd�Zd	d
�Zdd�Zd
d�Zdd�Zdd�Zdd�ZdS)z|
    pyudev._util
    ============

    Internal utilities

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
�)�print_function�division�unicode_literals�absolute_import)�check_outputNcCst|t�s|jtj��}|S)z�
    Return the given ``value`` as bytestring.

    If the given ``value`` is not a byte string, but a real unicode string, it
    is encoded with the filesystem encoding (as in
    :func:`sys.getfilesystemencoding()`).
    )�
isinstance�bytes�encode�sys�getfilesystemencoding)�value�r
�/usr/lib/python3.6/_util.py�ensure_byte_string-s
rcCst|tj�s|jtj��}|S)z�
    Return the given ``value`` as unicode string.

    If the given ``value`` is not a unicode string, but a byte string, it is
    decoded with the filesystem encoding (as in
    :func:`sys.getfilesystemencoding()`).
    )r�six�	text_type�decoder
r)rr
r
r�ensure_unicode_string:srcCs2t|t�rt|�}t|t�r |Sttj|��SdS)a�
    Return a byte string, which represents the given ``value`` in a way
    suitable as raw value of an udev property.

    If ``value`` is a boolean object, it is converted to ``'1'`` or ``'0'``,
    depending on whether ``value`` is ``True`` or ``False``.  If ``value`` is a
    byte string already, it is returned unchanged.  Anything else is simply
    converted to a unicode string, and then passed to
    :func:`ensure_byte_string`.
    N)r�bool�intrrrr)rr
r
r�property_value_to_bytesGs


rcCs|dkrtdj|���|dkS)z�
    Convert the given unicode string ``value`` to a boolean object.

    If ``value`` is ``'1'``, ``True`` is returned.  If ``value`` is ``'0'``,
    ``False`` is returned.  Any other value raises a
    :exc:`~exceptions.ValueError`.
    �1�0zNot a boolean value: {0!r})rr)�
ValueError�format)rr
r
r�string_to_bool\srccs6x0|r0|j|�}|j|�}||fV|j|�}qWdS)z�
    Iteration helper for udev list entry objects.

    Yield a tuple ``(name, value)``.  ``name`` and ``value`` are bytestrings
    containing the name and the value of the list entry.  The exact contents
    depend on the list iterated over.
    N)Zudev_list_entry_get_nameZudev_list_entry_get_valueZudev_list_entry_get_next)Zlibudev�entry�namerr
r
r�udev_list_iterateis



rcCs:tj|�j}tj|�rdStj|�r(dStdj|���dS)a�
    Get the device type of a device file.

    ``filename`` is a string containing the path of a device file.

    Return ``'char'`` if ``filename`` is a character device, or ``'block'`` if
    ``filename`` is a block device.  Raise :exc:`~exceptions.ValueError` if
    ``filename`` is no device file at all.  Raise
    :exc:`~exceptions.EnvironmentError` if ``filename`` does not exist or if
    its metadata was inaccessible.

    .. versionadded:: 0.15
    �char�blockznot a device file: {0!r}N)�os�stat�st_mode�S_ISCHR�S_ISBLKrr)�filename�moder
r
r�get_device_typexs

r(cOsvddl}xhy
|||�Stt|jfk
rl}z4t|ttf�rD|j}n
|jd}|tjkrZw
�WYdd}~Xq
Xq
WdS)a=
    Handle interruptions to an interruptible system call.

    Run an interruptible system call in a loop and retry if it raises EINTR.
    The signal calls that may raise EINTR prior to Python 3.5 are listed in
    PEP 0475.  Any calls to these functions must be wrapped in eintr_retry_call
    in order to handle EINTR returns in older versions of Python.

    This function is safe to use under Python 3.5 and newer since the wrapped
    function will simply return without raising EINTR.

    This function is based on _eintr_retry_call in python's subprocess.py.
    rN)�select�OSError�IOError�errorr�errno�argsZEINTR)�funcr.�kwargsr)�errZ
error_coder
r
r�eintr_retry_call�s


r2cCsttddg��}t|j��S)ak
    Get the version of the underlying udev library.

    udev doesn't use a standard major-minor versioning scheme, but instead
    labels releases with a single consecutive number.  Consequently, the
    version number returned by this function is a single integer, and not a
    tuple (like for instance the interpreter version in
    :data:`sys.version_info`).

    As libudev itself does not provide a function to query the version number,
    this function calls the ``udevadm`` utility, so be prepared to catch
    :exc:`~exceptions.EnvironmentError` and
    :exc:`~subprocess.CalledProcessError` if you call this function.

    Return the version number as single integer.  Raise
    :exc:`~exceptions.ValueError`, if the version number retrieved from udev
    could not be converted to an integer.  Raise
    :exc:`~exceptions.EnvironmentError`, if ``udevadm`` was not found, or could
    not be executed.  Raise :exc:`subprocess.CalledProcessError`, if
    ``udevadm`` returned a non-zero exit code.  On Python 2.7 or newer, the
    ``output`` attribute of this exception is correctly set.

    .. versionadded:: 0.8
    Zudevadmz	--version)rrr�strip)�outputr
r
r�udev_version�sr5)�__doc__Z
__future__rrrr�
subprocessr�ImportErrorZpyudev._compatr!r
r"r-rrrrrrr(r2r5r
r
r
r�<module>s$


!monitor.py000064400000050730150351420040006604 0ustar00# -*- coding: utf-8 -*-
# Copyright (C) 2010, 2011, 2012, 2013 Sebastian Wiesner <lunaryorn@gmail.com>

# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.

# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
# for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA


"""
    pyudev.monitor
    ==============

    Monitor implementation.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
"""


from __future__ import (print_function, division, unicode_literals,
                        absolute_import)

import os
import errno
from threading import Thread
from functools import partial

from pyudev.device import Device

from pyudev._util import eintr_retry_call
from pyudev._util import ensure_byte_string

from pyudev._os import pipe
from pyudev._os import poll


class Monitor(object):
    """
    A synchronous device event monitor.

    A :class:`Monitor` objects connects to the udev daemon and listens for
    changes to the device list.  A monitor is created by connecting to the
    kernel daemon through netlink (see :meth:`from_netlink`):

    >>> from pyudev import Context, Monitor
    >>> context = Context()
    >>> monitor = Monitor.from_netlink(context)

    Once the monitor is created, you can add a filter using :meth:`filter_by()`
    or :meth:`filter_by_tag()` to drop incoming events in subsystems, which are
    not of interest to the application:

    >>> monitor.filter_by('input')

    When the monitor is eventually set up, you can either poll for events
    synchronously:

    >>> device = monitor.poll(timeout=3)
    >>> if device:
    ...     print('{0.action}: {0}'.format(device))
    ...

    Or you can monitor events asynchronously with :class:`MonitorObserver`.

    To integrate into various event processing frameworks, the monitor provides
    a :func:`selectable <select.select>` file description by :meth:`fileno()`.
    However, do *not*  read or write directly on this file descriptor.

    Instances of this class can directly be given as ``udev_monitor *`` to
    functions wrapped through :mod:`ctypes`.

    .. versionchanged:: 0.16
       Remove :meth:`from_socket()` which is deprecated, and even removed in
       recent udev versions.
    """

    def __init__(self, context, monitor_p):
        self.context = context
        self._as_parameter_ = monitor_p
        self._libudev = context._libudev
        self._started = False

    def __del__(self):
        self._libudev.udev_monitor_unref(self)

    @classmethod
    def from_netlink(cls, context, source='udev'):
        """
        Create a monitor by connecting to the kernel daemon through netlink.

        ``context`` is the :class:`Context` to use.  ``source`` is a string,
        describing the event source.  Two sources are available:

        ``'udev'`` (the default)
          Events emitted after udev as registered and configured the device.
          This is the absolutely recommended source for applications.

        ``'kernel'``
          Events emitted directly after the kernel has seen the device.  The
          device has not yet been configured by udev and might not be usable
          at all.  **Never** use this, unless you know what you are doing.

        Return a new :class:`Monitor` object, which is connected to the
        given source.  Raise :exc:`~exceptions.ValueError`, if an invalid
        source has been specified.  Raise
        :exc:`~exceptions.EnvironmentError`, if the creation of the monitor
        failed.
        """
        if source not in ('kernel', 'udev'):
            raise ValueError('Invalid source: {0!r}. Must be one of "udev" '
                             'or "kernel"'.format(source))
        monitor = context._libudev.udev_monitor_new_from_netlink(
            context, ensure_byte_string(source))
        if not monitor:
            raise EnvironmentError('Could not create udev monitor')
        return cls(context, monitor)

    @property
    def started(self):
        """
        ``True``, if this monitor was started, ``False`` otherwise. Readonly.

        .. seealso:: :meth:`start()`
        .. versionadded:: 0.16
        """
        return self._started

    def fileno(self):
        # pylint: disable=anomalous-backslash-in-string
        """
        Return the file description associated with this monitor as integer.

        This is really a real file descriptor ;), which can be watched and
        :func:`select.select`\ ed.
        """
        return self._libudev.udev_monitor_get_fd(self)

    def filter_by(self, subsystem, device_type=None):
        """
        Filter incoming events.

        ``subsystem`` is a byte or unicode string with the name of a
        subsystem (e.g. ``'input'``).  Only events originating from the
        given subsystem pass the filter and are handed to the caller.

        If given, ``device_type`` is a byte or unicode string specifying the
        device type.  Only devices with the given device type are propagated
        to the caller.  If ``device_type`` is not given, no additional
        filter for a specific device type is installed.

        These filters are executed inside the kernel, and client processes
        will usually not be woken up for device, that do not match these
        filters.

        .. versionchanged:: 0.15
           This method can also be after :meth:`start()` now.
        """
        subsystem = ensure_byte_string(subsystem)
        if device_type is not None:
            device_type = ensure_byte_string(device_type)
        self._libudev.udev_monitor_filter_add_match_subsystem_devtype(
            self, subsystem, device_type)
        self._libudev.udev_monitor_filter_update(self)

    def filter_by_tag(self, tag):
        """
        Filter incoming events by the given ``tag``.

        ``tag`` is a byte or unicode string with the name of a tag.  Only
        events for devices which have this tag attached pass the filter and are
        handed to the caller.

        Like with :meth:`filter_by` this filter is also executed inside the
        kernel, so that client processes are usually not woken up for devices
        without the given ``tag``.

        .. udevversion:: 154

        .. versionadded:: 0.9

        .. versionchanged:: 0.15
           This method can also be after :meth:`start()` now.
        """
        self._libudev.udev_monitor_filter_add_match_tag(
            self, ensure_byte_string(tag))
        self._libudev.udev_monitor_filter_update(self)

    def remove_filter(self):
        """
        Remove any filters installed with :meth:`filter_by()` or
        :meth:`filter_by_tag()` from this monitor.

        .. warning::

           Up to udev 181 (and possibly even later versions) the underlying
           ``udev_monitor_filter_remove()`` seems to be broken.  If used with
           affected versions this method always raises
           :exc:`~exceptions.ValueError`.

        Raise :exc:`~exceptions.EnvironmentError` if removal of installed
        filters failed.

        .. versionadded:: 0.15
        """
        self._libudev.udev_monitor_filter_remove(self)
        self._libudev.udev_monitor_filter_update(self)

    def enable_receiving(self):
        """
        Switch the monitor into listing mode.

        Connect to the event source and receive incoming events.  Only after
        calling this method, the monitor listens for incoming events.

        .. note::

           This method is implicitly called by :meth:`__iter__`.  You don't
           need to call it explicitly, if you are iterating over the
           monitor.

        .. deprecated:: 0.16
           Will be removed in 1.0. Use :meth:`start()` instead.
        """
        import warnings
        warnings.warn('Will be removed in 1.0. Use Monitor.start() instead.',
                      DeprecationWarning)
        self.start()

    def start(self):
        """
        Start this monitor.

        The monitor will not receive events until this method is called. This
        method does nothing if called on an already started :class:`Monitor`.

        .. note::

           Typically you don't need to call this method. It is implicitly
           called by :meth:`poll()` and :meth:`__iter__()`.

        .. seealso:: :attr:`started`
        .. versionchanged:: 0.16
           This method does nothing if the :class:`Monitor` was already
           started.
        """
        if not self._started:
            self._libudev.udev_monitor_enable_receiving(self)
            # Force monitor FD into non-blocking mode
            pipe.set_fd_status_flag(self, os.O_NONBLOCK)
            self._started = True

    def set_receive_buffer_size(self, size):
        """
        Set the receive buffer ``size``.

        ``size`` is the requested buffer size in bytes, as integer.

        .. note::

           The CAP_NET_ADMIN capability must be contained in the effective
           capability set of the caller for this method to succeed.  Otherwise
           :exc:`~exceptions.EnvironmentError` will be raised, with ``errno``
           set to :data:`~errno.EPERM`.  Unprivileged processes typically lack
           this capability.  You can check the capabilities of the current
           process with the python-prctl_ module:

           >>> import prctl
           >>> prctl.cap_effective.net_admin

        Raise :exc:`~exceptions.EnvironmentError`, if the buffer size could not
        bet set.

        .. versionadded:: 0.13

        .. _python-prctl: http://packages.python.org/python-prctl
        """
        self._libudev.udev_monitor_set_receive_buffer_size(self, size)

    def _receive_device(self):
        """Receive a single device from the monitor.

        Return the received :class:`Device`, or ``None`` if no device could be
        received.

        """
        while True:
            try:
                device_p = self._libudev.udev_monitor_receive_device(self)
                return Device(self.context, device_p) if device_p else None
            except EnvironmentError as error:
                if error.errno in (errno.EAGAIN, errno.EWOULDBLOCK):
                    # No data available
                    return None
                elif error.errno == errno.EINTR:
                    # Try again if our system call was interrupted
                    continue
                else:
                    raise

    def poll(self, timeout=None):
        """
        Poll for a device event.

        You can use this method together with :func:`iter()` to synchronously
        monitor events in the current thread::

           for device in iter(monitor.poll, None):
               print('{0.action} on {0.device_path}'.format(device))

        Since this method will never return ``None`` if no ``timeout`` is
        specified, this is effectively an endless loop. With
        :func:`functools.partial()` you can also create a loop that only waits
        for a specified time::

           for device in iter(partial(monitor.poll, 3), None):
               print('{0.action} on {0.device_path}'.format(device))

        This loop will only wait three seconds for a new device event. If no
        device event occurred after three seconds, the loop will exit.

        ``timeout`` is a floating point number that specifies a time-out in
        seconds. If omitted or ``None``, this method blocks until a device
        event is available. If ``0``, this method just polls and will never
        block.

        .. note::

           This method implicitly calls :meth:`start()`.

        Return the received :class:`Device`, or ``None`` if a timeout
        occurred. Raise :exc:`~exceptions.EnvironmentError` if event retrieval
        failed.

        .. seealso::

           :attr:`Device.action`
              The action that created this event.

           :attr:`Device.sequence_number`
              The sequence number of this event.

        .. versionadded:: 0.16
        """
        if timeout is not None and timeout > 0:
            # .poll() takes timeout in milliseconds
            timeout = int(timeout * 1000)
        self.start()
        if eintr_retry_call(poll.Poll.for_events((self, 'r')).poll, timeout):
            return self._receive_device()
        else:
            return None

    def receive_device(self):
        """
        Receive a single device from the monitor.

        .. warning::

           You *must* call :meth:`start()` before calling this method.

        The caller must make sure, that there are events available in the
        event queue.  The call blocks, until a device is available.

        If a device was available, return ``(action, device)``.  ``device``
        is the :class:`Device` object describing the device.  ``action`` is
        a string describing the action.  Usual actions are:

        ``'add'``
          A device has been added (e.g. a USB device was plugged in)
        ``'remove'``
          A device has been removed (e.g. a USB device was unplugged)
        ``'change'``
          Something about the device changed (e.g. a device property)
        ``'online'``
          The device is online now
        ``'offline'``
          The device is offline now

        Raise :exc:`~exceptions.EnvironmentError`, if no device could be
        read.

        .. deprecated:: 0.16
           Will be removed in 1.0. Use :meth:`Monitor.poll()` instead.
        """
        import warnings
        warnings.warn('Will be removed in 1.0. Use Monitor.poll() instead.',
                      DeprecationWarning)
        device = self.poll()
        return device.action, device

    def __iter__(self):
        """
        Wait for incoming events and receive them upon arrival.

        This methods implicitly calls :meth:`start()`, and starts polling the
        :meth:`fileno` of this monitor.  If a event comes in, it receives the
        corresponding device and yields it to the caller.

        The returned iterator is endless, and continues receiving devices
        without ever stopping.

        Yields ``(action, device)`` (see :meth:`receive_device` for a
        description).

        .. deprecated:: 0.16
           Will be removed in 1.0. Use an explicit loop over :meth:`poll()`
           instead, or monitor asynchronously with :class:`MonitorObserver`.
        """
        import warnings
        warnings.warn('Will be removed in 1.0. Use an explicit loop over '
                      '"poll()" instead, or monitor asynchronously with '
                      '"MonitorObserver".', DeprecationWarning)
        self.start()
        while True:
            device = self.poll()
            if device is not None:
                yield device.action, device


class MonitorObserver(Thread):
    """
    An asynchronous observer for device events.

    This class subclasses :class:`~threading.Thread` class to asynchronously
    observe a :class:`Monitor` in a background thread:

    >>> from pyudev import Context, Monitor, MonitorObserver
    >>> context = Context()
    >>> monitor = Monitor.from_netlink(context)
    >>> monitor.filter_by(subsystem='input')
    >>> def print_device_event(device):
    ...     print('background event {0.action}: {0.device_path}'.format(device))
    >>> observer = MonitorObserver(monitor, callback=print_device_event, name='monitor-observer')
    >>> observer.daemon
    True
    >>> observer.start()

    In the above example, input device events will be printed in background,
    until :meth:`stop()` is called on ``observer``.

    .. note::

       Instances of this class are always created as daemon thread.  If you do
       not want to use daemon threads for monitoring, you need explicitly set
       :attr:`~threading.Thread.daemon` to ``False`` before invoking
       :meth:`~threading.Thread.start()`.

    .. seealso::

       :attr:`Device.action`
          The action that created this event.

       :attr:`Device.sequence_number`
          The sequence number of this event.

    .. versionadded:: 0.14

    .. versionchanged:: 0.15
       :meth:`Monitor.start()` is implicitly called when the thread is started.
    """

    def __init__(self, monitor, event_handler=None, callback=None, *args,
                 **kwargs):
        """
        Create a new observer for the given ``monitor``.

        ``monitor`` is the :class:`Monitor` to observe. ``callback`` is the
        callable to invoke on events, with the signature ``callback(device)``
        where ``device`` is the :class:`Device` that caused the event.

        .. warning::

           ``callback`` is invoked in the observer thread, hence the observer
           is blocked while callback executes.

        ``args`` and ``kwargs`` are passed unchanged to the constructor of
        :class:`~threading.Thread`.

        .. deprecated:: 0.16
           The ``event_handler`` argument will be removed in 1.0. Use
           the ``callback`` argument instead.
        .. versionchanged:: 0.16
           Add ``callback`` argument.
        """
        if callback is None and event_handler is None:
            raise ValueError('callback missing')
        elif callback is not None and event_handler is not None:
            raise ValueError('Use either callback or event handler')

        Thread.__init__(self, *args, **kwargs)
        self.monitor = monitor
        # observer threads should not keep the interpreter alive
        self.daemon = True
        self._stop_event = None
        if event_handler is not None:
            import warnings
            warnings.warn('"event_handler" argument will be removed in 1.0. '
                          'Use Monitor.poll() instead.', DeprecationWarning)
            callback = lambda d: event_handler(d.action, d)
        self._callback = callback

    def start(self):
        """Start the observer thread."""
        if not self.is_alive():
            self._stop_event = pipe.Pipe.open()
        Thread.start(self)

    def run(self):
        self.monitor.start()
        notifier = poll.Poll.for_events(
            (self.monitor, 'r'), (self._stop_event.source, 'r'))
        while True:
            for file_descriptor, event in eintr_retry_call(notifier.poll):
                if file_descriptor == self._stop_event.source.fileno():
                    # in case of a stop event, close our pipe side, and
                    # return from the thread
                    self._stop_event.source.close()
                    return
                elif file_descriptor == self.monitor.fileno() and event == 'r':
                    read_device = partial(eintr_retry_call, self.monitor.poll, timeout=0)
                    for device in iter(read_device, None):
                        self._callback(device)
                else:
                    raise EnvironmentError('Observed monitor hung up')

    def send_stop(self):
        """
        Send a stop signal to the background thread.

        The background thread will eventually exit, but it may still be running
        when this method returns.  This method is essentially the asynchronous
        equivalent to :meth:`stop()`.

        .. note::

           The underlying :attr:`monitor` is *not* stopped.
        """
        if self._stop_event is None:
            return
        with self._stop_event.sink:
            # emit a stop event to the thread
            eintr_retry_call(self._stop_event.sink.write, b'\x01')
            self._stop_event.sink.flush()

    def stop(self):
        """
        Synchronously stop the background thread.

        .. note::

           This method can safely be called from the observer thread. In this
           case it is equivalent to :meth:`send_stop()`.

        Send a stop signal to the backgroud (see :meth:`send_stop`), and waits
        for the background thread to exit (see :meth:`~threading.Thread.join`)
        if the current thread is *not* the observer thread.

        After this method returns in a thread *that is not the observer
        thread*, the ``callback`` is guaranteed to not be invoked again
        anymore.

        .. note::

           The underlying :attr:`monitor` is *not* stopped.

        .. versionchanged:: 0.16
           This method can be called from the observer thread.
        """
        self.send_stop()
        try:
            self.join()
        except RuntimeError:
            pass
_ctypeslib/__init__.py000064400000001717150351420040011012 0ustar00# -*- coding: utf-8 -*-
# Copyright (C) 2015 mulhern <amulhern@redhat.com>

# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.

# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
# for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

"""
    pyudev._ctypeslib
    =================

    Wrappers for libraries.

    .. moduleauthor::  mulhern  <amulhern@redhat.com>
"""

from . import libc
from . import libudev
_ctypeslib/__pycache__/_errorcheckers.cpython-36.opt-1.pyc000064400000004555150351420040017501 0ustar003

u1�W��@s�dZddlmZddlmZddlmZddlmZddlZddlZddlm	Z	ej
eeje
ejeiZdd	�Zd
d�Zdd
�Zdd�ZdS)zt
    pyudev._ctypeslib._errorcheckers
    ================================

    Error checkers for ctypes wrappers.
�)�absolute_import)�division)�print_function)�unicode_literalsN)�	get_errnocCs2tj|�}tj|�}|dk	r$||�St||�SdS)z�Create an exception from ``errnum``.

    ``errnum`` is an integral error number.

    Return an exception object appropriate to ``errnum``.

    N)�ERRNO_EXCEPTIONS�get�os�strerror�EnvironmentError)�errnumZ	exceptionZerrorstr�r
�$/usr/lib/python3.6/_errorcheckers.py�exception_from_errno+s


rcGs |dkr|}t|��n|SdS)a�Error checker for funtions, which return negative error codes.

    If ``result`` is smaller than ``0``, it is interpreted as negative error
    code, and an appropriate exception is raised:

    - ``-ENOMEM`` raises a :exc:`~exceptions.MemoryError`
    - ``-EOVERFLOW`` raises a :exc:`~exceptions.OverflowError`
    - all other error codes raise :exc:`~exceptions.EnvironmentError`

    If result is greater or equal to ``0``, it is returned unchanged.

    rN)r)�result�func�argsrr
r
r�check_negative_errorcode;s

rcGs"|dkrt�}|dkrt|��|S)z�Error checker to check the system ``errno`` as returned by
    :func:`ctypes.get_errno()`.

    If ``result`` is not ``0``, an exception according to this errno is raised.
    Otherwise nothing happens.

    r)rr)rrrrr
r
r�check_errno_on_nonzero_returnPs
rcGs|st�}|dkrt|��|S)z�Error checker to check the system ``errno`` as returned by
    :func:`ctypes.get_errno()`.

    If ``result`` is a null pointer, an exception according to this errno is
    raised.  Otherwise nothing happens.

    r)rr)rrrrr
r
r�"check_errno_on_null_pointer_return_s
	r)�__doc__Z
__future__rrrrr	�errnoZctypesrZENOMEM�MemoryErrorZ	EOVERFLOW�
OverflowErrorZEINVAL�
ValueErrorrrrrrr
r
r
r�<module>s
_ctypeslib/__pycache__/libc.cpython-36.opt-1.pyc000064400000001177150351420040015407 0ustar003

u1�W<�@stdZddlmZddlmZddlmZddlmZddlmZddlm	Z	ed	Z
ee
egefd
�Zee	d
�Z
dS)z�
    pyudev._ctypeslib.libc
    ======================

    Wrappers for libc.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
�)�absolute_import)�division)�print_function)�unicode_literals)�c_int�)�check_errno_on_nonzero_return�)�pipe2N)�__doc__Z
__future__rrrrZctypesrZ_errorcheckersrZfd_pair�dictZ
SIGNATURESZERROR_CHECKERS�r
r
�/usr/lib/python3.6/libc.py�<module>s_ctypeslib/__pycache__/utils.cpython-36.opt-1.pyc000064400000003126150351420040015632 0ustar003

u1�W�	�@sXdZddlmZddlmZddlmZddlmZddlmZddlm	Z	dd	�Z
d
S)z�
    pyudev._ctypeslib.utils
    =======================

    Utilities for loading ctypeslib.

    .. moduleauthor::  Anne Mulhern  <amulhern@redhat.com>
�)�absolute_import)�division)�print_function)�unicode_literals)�CDLL)�find_librarycCsvt|�}|std|��t|dd�}xL|j�D]@\}}t||d�}|r.|\}}	||_|	|_|j|�}
|
r.|
|_q.W|S)a{
    Load library ``name`` and return a :class:`ctypes.CDLL` object for it.

    :param str name: the library name
    :param signatures: signatures of methods
    :type signatures: dict of str * (tuple of (list of type) * type)
    :param error_checkers: error checkers for methods
    :type error_checkers: dict of str * ((int * ptr * arglist) -> int)

    The library has errno handling enabled.
    Important functions are given proper signatures and return types to support
    type checking and argument conversion.

    :returns: a loaded library
    :rtype: ctypes.CDLL
    :raises ImportError: if the library is not found
    zNo library named %sT)Z	use_errnoN)	r�ImportErrorr�items�getattr�argtypes�restype�getZerrcheck)�nameZ
signaturesZerror_checkersZlibrary_name�lib�funcnameZ	signatureZfunctionrrZerrorchecker�r�/usr/lib/python3.6/utils.py�load_ctypes_library$s

rN)�__doc__Z
__future__rrrrZctypesrZctypes.utilrrrrrr�<module>s_ctypeslib/__pycache__/libc.cpython-36.pyc000064400000001177150351420040014450 0ustar003

u1�W<�@stdZddlmZddlmZddlmZddlmZddlmZddlm	Z	ed	Z
ee
egefd
�Zee	d
�Z
dS)z�
    pyudev._ctypeslib.libc
    ======================

    Wrappers for libc.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
�)�absolute_import)�division)�print_function)�unicode_literals)�c_int�)�check_errno_on_nonzero_return�)�pipe2N)�__doc__Z
__future__rrrrZctypesrZ_errorcheckersrZfd_pair�dictZ
SIGNATURESZERROR_CHECKERS�r
r
�/usr/lib/python3.6/libc.py�<module>s_ctypeslib/__pycache__/libudev.cpython-36.opt-1.pyc000064400000013134150351420040016124 0ustar003

u1�W+*�I@sfdZddlmZddlmZddlmZddlmZddlmZddlmZddlm	Z	dd	lm
Z
dd
lmZddlmZddlm
Z
dd
lmZddlmZddlmZddlmZddlmZGdd�de
�Zee�ZGdd�de
�Zee�ZGdd�de
�Zee�ZGdd�de
�Zee�ZGdd�de
�Zee�ZGdd�de
�Zee�Z eZ!e"gefegdfegefegefegefegefege	fee	gdfegefegefegdfeege	feege	feeege	feeege	feeege	feege	feege	feege	fege	fege	fegefegefegefegefegefegdfeegefeeegefeee!gefeegefegefegefeeegefegefegefegefegefegefegefegefegefeegefeegefege!fegefegefege	fegefegefegefegefegefeeege	feege	fegefegdfeegefege	fee	ge	fege	fegefeeege	feege	fege	fege	fe ge fe gdfege fe ee
gefd �FZ#e"dddddddddddddddddddddddddddddeeeeeeeeeeddddddddddddddddeeedeeeedddddddd!�FZ$dS)"z�
    pyudev._ctypeslib.libudev
    =========================

    Wrapper types for libudev.  Use ``libudev`` attribute to access libudev
    functions.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
�)�absolute_import)�division)�print_function)�unicode_literals)�c_char)�c_char_p)�c_int)�c_uint)�c_ulonglong)�CDLL)�	Structure)�POINTER)�find_library�)�check_errno_on_nonzero_return)�"check_errno_on_null_pointer_return)�check_negative_errorcodec@seZdZdZdS)�udevz'
    Dummy for ``udev`` structure.
    N)�__name__�
__module__�__qualname__�__doc__�rr�/usr/lib/python3.6/libudev.pyr2src@seZdZdZdS)�udev_enumeratez1
    Dummy for ``udev_enumerate`` structure.
    N)rrrrrrrrr<src@seZdZdZdS)�udev_list_entryz2
    Dummy for ``udev_list_entry`` structure.
    N)rrrrrrrrrFsrc@seZdZdZdS)�udev_devicez.
    Dummy for ``udev_device`` structure.
    N)rrrrrrrrrPsrc@seZdZdZdS)�udev_monitorz.
    Dummy for ``udev_device`` structure.
    N)rrrrrrrrrZsrc@seZdZdZdS)�	udev_hwdbz,
    Dummy for ``udev_hwdb`` structure.
    N)rrrrrrrrrcsrN)F�udev_new�
udev_unref�udev_ref�udev_get_sys_path�udev_get_dev_path�udev_get_run_path�udev_get_log_priority�udev_set_log_priority�udev_enumerate_new�udev_enumerate_ref�udev_enumerate_unref�"udev_enumerate_add_match_subsystem�$udev_enumerate_add_nomatch_subsystem�!udev_enumerate_add_match_property� udev_enumerate_add_match_sysattr�"udev_enumerate_add_nomatch_sysattr�udev_enumerate_add_match_tag� udev_enumerate_add_match_sysname�udev_enumerate_add_match_parent�'udev_enumerate_add_match_is_initialized�udev_enumerate_scan_devices�udev_enumerate_get_list_entry�udev_list_entry_get_next�udev_list_entry_get_name�udev_list_entry_get_value�udev_device_ref�udev_device_unref�udev_device_new_from_syspath�&udev_device_new_from_subsystem_sysname�udev_device_new_from_devnum�udev_device_new_from_device_id� udev_device_new_from_environment�udev_device_get_parent�-udev_device_get_parent_with_subsystem_devtype�udev_device_get_devpath�udev_device_get_subsystem�udev_device_get_syspath�udev_device_get_sysnum�udev_device_get_sysname�udev_device_get_driver�udev_device_get_devtype�udev_device_get_devnode�udev_device_get_property_value�udev_device_get_sysattr_value�udev_device_get_devnum�udev_device_get_action�udev_device_get_seqnum�udev_device_get_is_initialized�&udev_device_get_usec_since_initialized�#udev_device_get_devlinks_list_entry�udev_device_get_tags_list_entry�%udev_device_get_properties_list_entry�"udev_device_get_sysattr_list_entry�udev_device_set_sysattr_value�udev_device_has_tag�udev_monitor_ref�udev_monitor_unref�udev_monitor_new_from_netlink�udev_monitor_enable_receiving�$udev_monitor_set_receive_buffer_size�udev_monitor_get_fd�udev_monitor_receive_device�/udev_monitor_filter_add_match_subsystem_devtype�!udev_monitor_filter_add_match_tag�udev_monitor_filter_update�udev_monitor_filter_remove�
udev_hwdb_ref�udev_hwdb_unref�
udev_hwdb_new�#udev_hwdb_get_properties_list_entry)FrLrPrHrKrArGrFrNr?r@rRrIrMrBrSrJrErDrCrQrOrUr=r<r>r;r:r8r9rTr1r*r+r,r-r.r/r0r2r4r'r(r3r)r#r%r$r"rdrcrarbr6r5r7rZrYr\rVr]r^r_r`r[rXrWrr!r&r )%rZ
__future__rrrrZctypesrrrr	r
rrr
Zctypes.utilrZ_errorcheckersrrrrZudev_prZudev_enumerate_prZudev_list_entry_prZ
udev_device_prZudev_monitor_prZudev_hwdb_pZdev_t�dictZ
SIGNATURESZERROR_CHECKERSrrrr�<module>sb














_ctypeslib/__pycache__/__init__.cpython-36.pyc000064400000000476150351420040015277 0ustar003

H�V��@s dZddlmZddlmZdS)z�
    pyudev._ctypeslib
    =================

    Wrappers for libraries.

    .. moduleauthor::  mulhern  <amulhern@redhat.com>
�)�libc)�libudevN)�__doc__�rr�rr�/usr/lib/python3.6/__init__.py�<module>s_ctypeslib/__pycache__/__init__.cpython-36.opt-1.pyc000064400000000476150351420040016236 0ustar003

H�V��@s dZddlmZddlmZdS)z�
    pyudev._ctypeslib
    =================

    Wrappers for libraries.

    .. moduleauthor::  mulhern  <amulhern@redhat.com>
�)�libc)�libudevN)�__doc__�rr�rr�/usr/lib/python3.6/__init__.py�<module>s_ctypeslib/__pycache__/libudev.cpython-36.pyc000064400000013134150351420040015165 0ustar003

u1�W+*�I@sfdZddlmZddlmZddlmZddlmZddlmZddlmZddlm	Z	dd	lm
Z
dd
lmZddlmZddlm
Z
dd
lmZddlmZddlmZddlmZddlmZGdd�de
�Zee�ZGdd�de
�Zee�ZGdd�de
�Zee�ZGdd�de
�Zee�ZGdd�de
�Zee�ZGdd�de
�Zee�Z eZ!e"gefegdfegefegefegefegefege	fee	gdfegefegefegdfeege	feege	feeege	feeege	feeege	feege	feege	feege	fege	fege	fegefegefegefegefegefegdfeegefeeegefeee!gefeegefegefegefeeegefegefegefegefegefegefegefegefegefeegefeegefege!fegefegefege	fegefegefegefegefegefeeege	feege	fegefegdfeegefege	fee	ge	fege	fegefeeege	feege	fege	fege	fe ge fe gdfege fe ee
gefd �FZ#e"dddddddddddddddddddddddddddddeeeeeeeeeeddddddddddddddddeeedeeeedddddddd!�FZ$dS)"z�
    pyudev._ctypeslib.libudev
    =========================

    Wrapper types for libudev.  Use ``libudev`` attribute to access libudev
    functions.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
�)�absolute_import)�division)�print_function)�unicode_literals)�c_char)�c_char_p)�c_int)�c_uint)�c_ulonglong)�CDLL)�	Structure)�POINTER)�find_library�)�check_errno_on_nonzero_return)�"check_errno_on_null_pointer_return)�check_negative_errorcodec@seZdZdZdS)�udevz'
    Dummy for ``udev`` structure.
    N)�__name__�
__module__�__qualname__�__doc__�rr�/usr/lib/python3.6/libudev.pyr2src@seZdZdZdS)�udev_enumeratez1
    Dummy for ``udev_enumerate`` structure.
    N)rrrrrrrrr<src@seZdZdZdS)�udev_list_entryz2
    Dummy for ``udev_list_entry`` structure.
    N)rrrrrrrrrFsrc@seZdZdZdS)�udev_devicez.
    Dummy for ``udev_device`` structure.
    N)rrrrrrrrrPsrc@seZdZdZdS)�udev_monitorz.
    Dummy for ``udev_device`` structure.
    N)rrrrrrrrrZsrc@seZdZdZdS)�	udev_hwdbz,
    Dummy for ``udev_hwdb`` structure.
    N)rrrrrrrrrcsrN)F�udev_new�
udev_unref�udev_ref�udev_get_sys_path�udev_get_dev_path�udev_get_run_path�udev_get_log_priority�udev_set_log_priority�udev_enumerate_new�udev_enumerate_ref�udev_enumerate_unref�"udev_enumerate_add_match_subsystem�$udev_enumerate_add_nomatch_subsystem�!udev_enumerate_add_match_property� udev_enumerate_add_match_sysattr�"udev_enumerate_add_nomatch_sysattr�udev_enumerate_add_match_tag� udev_enumerate_add_match_sysname�udev_enumerate_add_match_parent�'udev_enumerate_add_match_is_initialized�udev_enumerate_scan_devices�udev_enumerate_get_list_entry�udev_list_entry_get_next�udev_list_entry_get_name�udev_list_entry_get_value�udev_device_ref�udev_device_unref�udev_device_new_from_syspath�&udev_device_new_from_subsystem_sysname�udev_device_new_from_devnum�udev_device_new_from_device_id� udev_device_new_from_environment�udev_device_get_parent�-udev_device_get_parent_with_subsystem_devtype�udev_device_get_devpath�udev_device_get_subsystem�udev_device_get_syspath�udev_device_get_sysnum�udev_device_get_sysname�udev_device_get_driver�udev_device_get_devtype�udev_device_get_devnode�udev_device_get_property_value�udev_device_get_sysattr_value�udev_device_get_devnum�udev_device_get_action�udev_device_get_seqnum�udev_device_get_is_initialized�&udev_device_get_usec_since_initialized�#udev_device_get_devlinks_list_entry�udev_device_get_tags_list_entry�%udev_device_get_properties_list_entry�"udev_device_get_sysattr_list_entry�udev_device_set_sysattr_value�udev_device_has_tag�udev_monitor_ref�udev_monitor_unref�udev_monitor_new_from_netlink�udev_monitor_enable_receiving�$udev_monitor_set_receive_buffer_size�udev_monitor_get_fd�udev_monitor_receive_device�/udev_monitor_filter_add_match_subsystem_devtype�!udev_monitor_filter_add_match_tag�udev_monitor_filter_update�udev_monitor_filter_remove�
udev_hwdb_ref�udev_hwdb_unref�
udev_hwdb_new�#udev_hwdb_get_properties_list_entry)FrLrPrHrKrArGrFrNr?r@rRrIrMrBrSrJrErDrCrQrOrUr=r<r>r;r:r8r9rTr1r*r+r,r-r.r/r0r2r4r'r(r3r)r#r%r$r"rdrcrarbr6r5r7rZrYr\rVr]r^r_r`r[rXrWrr!r&r )%rZ
__future__rrrrZctypesrrrr	r
rrr
Zctypes.utilrZ_errorcheckersrrrrZudev_prZudev_enumerate_prZudev_list_entry_prZ
udev_device_prZudev_monitor_prZudev_hwdb_pZdev_t�dictZ
SIGNATURESZERROR_CHECKERSrrrr�<module>sb














_ctypeslib/__pycache__/_errorcheckers.cpython-36.pyc000064400000004555150351420040016542 0ustar003

u1�W��@s�dZddlmZddlmZddlmZddlmZddlZddlZddlm	Z	ej
eeje
ejeiZdd	�Zd
d�Zdd
�Zdd�ZdS)zt
    pyudev._ctypeslib._errorcheckers
    ================================

    Error checkers for ctypes wrappers.
�)�absolute_import)�division)�print_function)�unicode_literalsN)�	get_errnocCs2tj|�}tj|�}|dk	r$||�St||�SdS)z�Create an exception from ``errnum``.

    ``errnum`` is an integral error number.

    Return an exception object appropriate to ``errnum``.

    N)�ERRNO_EXCEPTIONS�get�os�strerror�EnvironmentError)�errnumZ	exceptionZerrorstr�r
�$/usr/lib/python3.6/_errorcheckers.py�exception_from_errno+s


rcGs |dkr|}t|��n|SdS)a�Error checker for funtions, which return negative error codes.

    If ``result`` is smaller than ``0``, it is interpreted as negative error
    code, and an appropriate exception is raised:

    - ``-ENOMEM`` raises a :exc:`~exceptions.MemoryError`
    - ``-EOVERFLOW`` raises a :exc:`~exceptions.OverflowError`
    - all other error codes raise :exc:`~exceptions.EnvironmentError`

    If result is greater or equal to ``0``, it is returned unchanged.

    rN)r)�result�func�argsrr
r
r�check_negative_errorcode;s

rcGs"|dkrt�}|dkrt|��|S)z�Error checker to check the system ``errno`` as returned by
    :func:`ctypes.get_errno()`.

    If ``result`` is not ``0``, an exception according to this errno is raised.
    Otherwise nothing happens.

    r)rr)rrrrr
r
r�check_errno_on_nonzero_returnPs
rcGs|st�}|dkrt|��|S)z�Error checker to check the system ``errno`` as returned by
    :func:`ctypes.get_errno()`.

    If ``result`` is a null pointer, an exception according to this errno is
    raised.  Otherwise nothing happens.

    r)rr)rrrrr
r
r�"check_errno_on_null_pointer_return_s
	r)�__doc__Z
__future__rrrrr	�errnoZctypesrZENOMEM�MemoryErrorZ	EOVERFLOW�
OverflowErrorZEINVAL�
ValueErrorrrrrrr
r
r
r�<module>s
_ctypeslib/__pycache__/utils.cpython-36.pyc000064400000003126150351420040014673 0ustar003

u1�W�	�@sXdZddlmZddlmZddlmZddlmZddlmZddlm	Z	dd	�Z
d
S)z�
    pyudev._ctypeslib.utils
    =======================

    Utilities for loading ctypeslib.

    .. moduleauthor::  Anne Mulhern  <amulhern@redhat.com>
�)�absolute_import)�division)�print_function)�unicode_literals)�CDLL)�find_librarycCsvt|�}|std|��t|dd�}xL|j�D]@\}}t||d�}|r.|\}}	||_|	|_|j|�}
|
r.|
|_q.W|S)a{
    Load library ``name`` and return a :class:`ctypes.CDLL` object for it.

    :param str name: the library name
    :param signatures: signatures of methods
    :type signatures: dict of str * (tuple of (list of type) * type)
    :param error_checkers: error checkers for methods
    :type error_checkers: dict of str * ((int * ptr * arglist) -> int)

    The library has errno handling enabled.
    Important functions are given proper signatures and return types to support
    type checking and argument conversion.

    :returns: a loaded library
    :rtype: ctypes.CDLL
    :raises ImportError: if the library is not found
    zNo library named %sT)Z	use_errnoN)	r�ImportErrorr�items�getattr�argtypes�restype�getZerrcheck)�nameZ
signaturesZerror_checkersZlibrary_name�lib�funcnameZ	signatureZfunctionrrZerrorchecker�r�/usr/lib/python3.6/utils.py�load_ctypes_library$s

rN)�__doc__Z
__future__rrrrZctypesrZctypes.utilrrrrrr�<module>s_ctypeslib/libudev.py000064400000025053150351420040010704 0ustar00# -*- coding: utf-8 -*-
# Copyright (C) 2010, 2011, 2012, 2013 Sebastian Wiesner <lunaryorn@gmail.com>

# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.

# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
# for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA


"""
    pyudev._ctypeslib.libudev
    =========================

    Wrapper types for libudev.  Use ``libudev`` attribute to access libudev
    functions.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from ctypes import c_char
from ctypes import c_char_p
from ctypes import c_int
from ctypes import c_uint
from ctypes import c_ulonglong
from ctypes import CDLL
from ctypes import Structure
from ctypes import POINTER

from ctypes.util import find_library

from ._errorcheckers import check_errno_on_nonzero_return
from ._errorcheckers import check_errno_on_null_pointer_return
from ._errorcheckers import check_negative_errorcode


class udev(Structure): # pylint: disable=invalid-name
    """
    Dummy for ``udev`` structure.
    """
    # pylint: disable=too-few-public-methods
    pass

udev_p = POINTER(udev) # pylint: disable=invalid-name


class udev_enumerate(Structure): # pylint: disable=invalid-name
    """
    Dummy for ``udev_enumerate`` structure.
    """
    # pylint: disable=too-few-public-methods
    pass

udev_enumerate_p = POINTER(udev_enumerate) # pylint: disable=invalid-name


class udev_list_entry(Structure): # pylint: disable=invalid-name
    """
    Dummy for ``udev_list_entry`` structure.
    """
    # pylint: disable=too-few-public-methods
    pass

udev_list_entry_p = POINTER(udev_list_entry) # pylint: disable=invalid-name


class udev_device(Structure): # pylint: disable=invalid-name
    """
    Dummy for ``udev_device`` structure.
    """
    # pylint: disable=too-few-public-methods
    pass

udev_device_p = POINTER(udev_device) # pylint: disable=invalid-name


class udev_monitor(Structure): # pylint: disable=invalid-name
    """
    Dummy for ``udev_device`` structure.
    """
    # pylint: disable=too-few-public-methods
    pass

udev_monitor_p = POINTER(udev_monitor) # pylint: disable=invalid-name

class udev_hwdb(Structure): # pylint: disable=invalid-name
    """
    Dummy for ``udev_hwdb`` structure.
    """
    # pylint: disable=too-few-public-methods
    pass

udev_hwdb_p = POINTER(udev_hwdb) # pylint: disable=invalid-name


dev_t = c_ulonglong # pylint: disable=invalid-name


SIGNATURES = dict(
   # context
   udev_new=([], udev_p),
   udev_unref=([udev_p], None),
   udev_ref=([udev_p], udev_p),
   udev_get_sys_path=([udev_p], c_char_p),
   udev_get_dev_path=([udev_p], c_char_p),
   udev_get_run_path=([udev_p], c_char_p),
   udev_get_log_priority=([udev_p], c_int),
   udev_set_log_priority=([udev_p, c_int], None),
   udev_enumerate_new=([udev_p], udev_enumerate_p),
   udev_enumerate_ref=([udev_enumerate_p], udev_enumerate_p),
   udev_enumerate_unref=([udev_enumerate_p], None),
   udev_enumerate_add_match_subsystem=([udev_enumerate_p, c_char_p], c_int),
   udev_enumerate_add_nomatch_subsystem=([udev_enumerate_p, c_char_p], c_int),
   udev_enumerate_add_match_property=(
      [udev_enumerate_p, c_char_p, c_char_p],
      c_int
   ),
   udev_enumerate_add_match_sysattr=(
      [udev_enumerate_p, c_char_p, c_char_p],
      c_int
   ),
   udev_enumerate_add_nomatch_sysattr=(
      [udev_enumerate_p, c_char_p, c_char_p],
      c_int
   ),
   udev_enumerate_add_match_tag=([udev_enumerate_p, c_char_p], c_int),
   udev_enumerate_add_match_sysname=([udev_enumerate_p, c_char_p], c_int),
   udev_enumerate_add_match_parent=([udev_enumerate_p, udev_device_p], c_int),
   udev_enumerate_add_match_is_initialized=([udev_enumerate_p], c_int),
   udev_enumerate_scan_devices=([udev_enumerate_p], c_int),
   udev_enumerate_get_list_entry=([udev_enumerate_p], udev_list_entry_p),
   # list entries
   udev_list_entry_get_next=([udev_list_entry_p], udev_list_entry_p),
   udev_list_entry_get_name=([udev_list_entry_p], c_char_p),
   udev_list_entry_get_value=([udev_list_entry_p], c_char_p),
   # devices
   udev_device_ref=([udev_device_p], udev_device_p),
   udev_device_unref=([udev_device_p], None),
   udev_device_new_from_syspath=([udev_p, c_char_p], udev_device_p),
   udev_device_new_from_subsystem_sysname=(
      [udev_p, c_char_p, c_char_p],
      udev_device_p
   ),
   udev_device_new_from_devnum=([udev_p, c_char, dev_t], udev_device_p),
   udev_device_new_from_device_id=([udev_p, c_char_p], udev_device_p),
   udev_device_new_from_environment=([udev_p], udev_device_p),
   udev_device_get_parent=([udev_device_p], udev_device_p),
   udev_device_get_parent_with_subsystem_devtype=(
      [udev_device_p, c_char_p, c_char_p],
      udev_device_p
   ),
   udev_device_get_devpath=([udev_device_p], c_char_p),
   udev_device_get_subsystem=([udev_device_p], c_char_p),
   udev_device_get_syspath=([udev_device_p], c_char_p),
   udev_device_get_sysnum=([udev_device_p], c_char_p),
   udev_device_get_sysname=([udev_device_p], c_char_p),
   udev_device_get_driver=([udev_device_p], c_char_p),
   udev_device_get_devtype=([udev_device_p], c_char_p),
   udev_device_get_devnode=([udev_device_p], c_char_p),
   udev_device_get_property_value=([udev_device_p, c_char_p], c_char_p),
   udev_device_get_sysattr_value=([udev_device_p, c_char_p], c_char_p),
   udev_device_get_devnum=([udev_device_p], dev_t),
   udev_device_get_action=([udev_device_p], c_char_p),
   udev_device_get_seqnum=([udev_device_p], c_ulonglong),
   udev_device_get_is_initialized=([udev_device_p], c_int),
   udev_device_get_usec_since_initialized=([udev_device_p], c_ulonglong),
   udev_device_get_devlinks_list_entry=([udev_device_p], udev_list_entry_p),
   udev_device_get_tags_list_entry=([udev_device_p], udev_list_entry_p),
   udev_device_get_properties_list_entry=([udev_device_p], udev_list_entry_p),
   udev_device_get_sysattr_list_entry=([udev_device_p], udev_list_entry_p),
   udev_device_set_sysattr_value=([udev_device_p, c_char_p, c_char_p], c_int),
   udev_device_has_tag=([udev_device_p, c_char_p], c_int),
   # monitoring
   udev_monitor_ref=([udev_monitor_p], udev_monitor_p),
   udev_monitor_unref=([udev_monitor_p], None),
   udev_monitor_new_from_netlink=([udev_p, c_char_p], udev_monitor_p),
   udev_monitor_enable_receiving=([udev_monitor_p], c_int),
   udev_monitor_set_receive_buffer_size=([udev_monitor_p, c_int], c_int),
   udev_monitor_get_fd=([udev_monitor_p], c_int),
   udev_monitor_receive_device=([udev_monitor_p], udev_device_p),
   udev_monitor_filter_add_match_subsystem_devtype=(
           [udev_monitor_p, c_char_p, c_char_p], c_int),
   udev_monitor_filter_add_match_tag=([udev_monitor_p, c_char_p], c_int),
   udev_monitor_filter_update=([udev_monitor_p], c_int),
   udev_monitor_filter_remove=([udev_monitor_p], c_int),
   # hwdb
   udev_hwdb_ref=([udev_hwdb_p], udev_hwdb_p),
   udev_hwdb_unref=([udev_hwdb_p], None),
   udev_hwdb_new=([udev_p], udev_hwdb_p),
   udev_hwdb_get_properties_list_entry=(
      [udev_hwdb_p, c_char_p, c_uint],
      udev_list_entry_p
   )
)


ERROR_CHECKERS = dict(
   udev_device_get_action=None,
   udev_device_get_devlinks_list_entry=None,
   udev_device_get_devnode=None,
   udev_device_get_devnum=None,
   udev_device_get_devpath=None,
   udev_device_get_devtype=None,
   udev_device_get_driver=None,
   udev_device_get_is_initialized=None,
   udev_device_get_parent=None,
   udev_device_get_parent_with_subsystem_devtype=None,
   udev_device_get_properties_list_entry=None,
   udev_device_get_property_value=None,
   udev_device_get_seqnum=None,
   udev_device_get_subsystem=None,
   udev_device_get_sysattr_list_entry=None,
   udev_device_get_sysattr_value=None,
   udev_device_get_sysname=None,
   udev_device_get_sysnum=None,
   udev_device_get_syspath=None,
   udev_device_get_tags_list_entry=None,
   udev_device_get_usec_since_initialized=None,
   udev_device_has_tag=None,
   udev_device_new_from_device_id=None,
   udev_device_new_from_devnum=None,
   udev_device_new_from_environment=None,
   udev_device_new_from_subsystem_sysname=None,
   udev_device_new_from_syspath=None,
   udev_device_ref=None,
   udev_device_unref=None,
   udev_device_set_sysattr_value=check_negative_errorcode,
   udev_enumerate_add_match_parent=check_negative_errorcode,
   udev_enumerate_add_match_subsystem=check_negative_errorcode,
   udev_enumerate_add_nomatch_subsystem=check_negative_errorcode,
   udev_enumerate_add_match_property=check_negative_errorcode,
   udev_enumerate_add_match_sysattr=check_negative_errorcode,
   udev_enumerate_add_nomatch_sysattr=check_negative_errorcode,
   udev_enumerate_add_match_tag=check_negative_errorcode,
   udev_enumerate_add_match_sysname=check_negative_errorcode,
   udev_enumerate_add_match_is_initialized=check_negative_errorcode,
   udev_enumerate_get_list_entry=None,
   udev_enumerate_new=None,
   udev_enumerate_ref=None,
   udev_enumerate_scan_devices=None,
   udev_enumerate_unref=None,
   udev_get_dev_path=None,
   udev_get_log_priority=None,
   udev_get_run_path=None,
   udev_get_sys_path=None,
   udev_hwdb_get_properties_list_entry=None,
   udev_hwdb_new=None,
   udev_hwdb_ref=None,
   udev_hwdb_unref=None,
   udev_list_entry_get_name=None,
   udev_list_entry_get_next=None,
   udev_list_entry_get_value=None,
   udev_monitor_set_receive_buffer_size=check_errno_on_nonzero_return,
   # libudev doc says, enable_receiving returns a negative errno, but tests
   # show that this is not reliable, so query the real error code
   udev_monitor_enable_receiving=check_errno_on_nonzero_return,
   udev_monitor_receive_device=check_errno_on_null_pointer_return,
   udev_monitor_ref=None,
   udev_monitor_filter_add_match_subsystem_devtype=check_negative_errorcode,
   udev_monitor_filter_add_match_tag=check_negative_errorcode,
   udev_monitor_filter_update=check_errno_on_nonzero_return,
   udev_monitor_filter_remove=check_errno_on_nonzero_return,
   udev_monitor_get_fd=None,
   udev_monitor_new_from_netlink=None,
   udev_monitor_unref=None,
   udev_new=None,
   udev_ref=None,
   udev_set_log_priority=None,
   udev_unref=None
)
_ctypeslib/utils.py000064400000004651150351420040010413 0ustar00# -*- coding: utf-8 -*-
# Copyright (C) 2013 Sebastian Wiesner <lunaryorn@gmail.com>

# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.

# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
# for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

"""
    pyudev._ctypeslib.utils
    =======================

    Utilities for loading ctypeslib.

    .. moduleauthor::  Anne Mulhern  <amulhern@redhat.com>
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from ctypes import CDLL
from ctypes.util import find_library


def load_ctypes_library(name, signatures, error_checkers):
    """
    Load library ``name`` and return a :class:`ctypes.CDLL` object for it.

    :param str name: the library name
    :param signatures: signatures of methods
    :type signatures: dict of str * (tuple of (list of type) * type)
    :param error_checkers: error checkers for methods
    :type error_checkers: dict of str * ((int * ptr * arglist) -> int)

    The library has errno handling enabled.
    Important functions are given proper signatures and return types to support
    type checking and argument conversion.

    :returns: a loaded library
    :rtype: ctypes.CDLL
    :raises ImportError: if the library is not found
    """
    library_name = find_library(name)
    if not library_name:
        raise ImportError('No library named %s' % name)
    lib = CDLL(library_name, use_errno=True)
    # Add function signatures
    for funcname, signature in signatures.items():
        function = getattr(lib, funcname, None)
        if function:
            argtypes, restype = signature
            function.argtypes = argtypes
            function.restype = restype
            errorchecker = error_checkers.get(funcname)
            if errorchecker:
                function.errcheck = errorchecker
    return lib
_ctypeslib/libc.py000064400000002474150351420040010165 0ustar00# -*- coding: utf-8 -*-
# Copyright (C) 2013 Sebastian Wiesner <lunaryorn@gmail.com>

# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.

# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
# for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

"""
    pyudev._ctypeslib.libc
    ======================

    Wrappers for libc.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from ctypes import c_int

from ._errorcheckers import check_errno_on_nonzero_return


fd_pair = c_int * 2


SIGNATURES = dict(
   pipe2=([fd_pair, c_int], c_int),
)

ERROR_CHECKERS = dict(
   pipe2=check_errno_on_nonzero_return,
)
_ctypeslib/_errorcheckers.py000064400000006241150351420040012250 0ustar00# -*- coding: utf-8 -*-
# Copyright (C) 2013 Sebastian Wiesner <lunaryorn@gmail.com>

# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.

# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
# for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

"""
    pyudev._ctypeslib._errorcheckers
    ================================

    Error checkers for ctypes wrappers.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals


import os
import errno
from ctypes import get_errno


ERRNO_EXCEPTIONS = {
    errno.ENOMEM: MemoryError,
    errno.EOVERFLOW: OverflowError,
    errno.EINVAL: ValueError
}


def exception_from_errno(errnum):
    """Create an exception from ``errnum``.

    ``errnum`` is an integral error number.

    Return an exception object appropriate to ``errnum``.

    """
    exception = ERRNO_EXCEPTIONS.get(errnum)
    errorstr = os.strerror(errnum)
    if exception is not None:
        return exception(errorstr)
    else:
        return EnvironmentError(errnum, errorstr)


def check_negative_errorcode(result, func, *args):
    """Error checker for funtions, which return negative error codes.

    If ``result`` is smaller than ``0``, it is interpreted as negative error
    code, and an appropriate exception is raised:

    - ``-ENOMEM`` raises a :exc:`~exceptions.MemoryError`
    - ``-EOVERFLOW`` raises a :exc:`~exceptions.OverflowError`
    - all other error codes raise :exc:`~exceptions.EnvironmentError`

    If result is greater or equal to ``0``, it is returned unchanged.

    """
    if result < 0:
        # udev returns the *negative* errno code at this point
        errnum = -result
        raise exception_from_errno(errnum)
    else:
        return result


def check_errno_on_nonzero_return(result, func, *args):
    """Error checker to check the system ``errno`` as returned by
    :func:`ctypes.get_errno()`.

    If ``result`` is not ``0``, an exception according to this errno is raised.
    Otherwise nothing happens.

    """
    if result != 0:
        errnum = get_errno()
        if errnum != 0:
            raise exception_from_errno(errnum)
    return result


def check_errno_on_null_pointer_return(result, func, *args):
    """Error checker to check the system ``errno`` as returned by
    :func:`ctypes.get_errno()`.

    If ``result`` is a null pointer, an exception according to this errno is
    raised.  Otherwise nothing happens.

    """
    # pylint: disable=invalid-name
    if not result:
        errnum = get_errno()
        if errnum != 0:
            raise exception_from_errno(errnum)
    return result
core.py000064400000032163150351420040006045 0ustar00# -*- coding: utf-8 -*-
# Copyright (C) 2010, 2011 Sebastian Wiesner <lunaryorn@gmail.com>

# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.

# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
# for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA


"""
    pyudev.core
    ===========

    Core types and functions of :mod:`pyudev`.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
"""


from __future__ import (print_function, division, unicode_literals,
                        absolute_import)

from pyudev.device import Devices
from pyudev.device._errors import DeviceNotFoundAtPathError
from pyudev._ctypeslib.libudev import ERROR_CHECKERS
from pyudev._ctypeslib.libudev import SIGNATURES
from pyudev._ctypeslib.utils import load_ctypes_library

from pyudev._util import ensure_byte_string
from pyudev._util import ensure_unicode_string
from pyudev._util import property_value_to_bytes
from pyudev._util import udev_list_iterate


class Context(object):
    """
    A device database connection.

    This class represents a connection to the udev device database, and is
    really *the* central object to access udev.  You need an instance of this
    class for almost anything else in pyudev.

    This class itself gives access to various udev configuration data (e.g.
    :attr:`sys_path`, :attr:`device_path`), and provides device enumeration
    (:meth:`list_devices()`).

    Instances of this class can directly be given as ``udev *`` to functions
    wrapped through :mod:`ctypes`.
    """

    def __init__(self):
        """
        Create a new context.
        """
        self._libudev = load_ctypes_library('udev', SIGNATURES, ERROR_CHECKERS)
        self._as_parameter_ = self._libudev.udev_new()

    def __del__(self):
        self._libudev.udev_unref(self)

    @property
    def sys_path(self):
        """
        The ``sysfs`` mount point defaulting to ``/sys'`` as unicode string.
        """
        if hasattr(self._libudev, 'udev_get_sys_path'):
            return ensure_unicode_string(self._libudev.udev_get_sys_path(self))
        else:
            # Fixed path since udev 183
            return '/sys'

    @property
    def device_path(self):
        """
        The device directory path defaulting to ``/dev`` as unicode string.
        """
        if hasattr(self._libudev, 'udev_get_dev_path'):
            return ensure_unicode_string(self._libudev.udev_get_dev_path(self))
        else:
            # Fixed path since udev 183
            return '/dev'

    @property
    def run_path(self):
        """
        The run runtime directory path defaulting to ``/run`` as unicode
        string.

        .. udevversion:: 167

        .. versionadded:: 0.10
        """
        if hasattr(self._libudev, 'udev_get_run_path'):
            return ensure_unicode_string(self._libudev.udev_get_run_path(self))
        else:
            return '/run/udev'

    @property
    def log_priority(self):
        """
        The logging priority of the interal logging facitility of udev as
        integer with a standard :mod:`syslog` priority.  Assign to this
        property to change the logging priority.

        UDev uses the standard :mod:`syslog` priorities.  Constants for these
        priorities are defined in the :mod:`syslog` module in the standard
        library:

        >>> import syslog
        >>> context = pyudev.Context()
        >>> context.log_priority = syslog.LOG_DEBUG

        .. versionadded:: 0.9
        """
        return self._libudev.udev_get_log_priority(self)

    @log_priority.setter
    def log_priority(self, value):
        """
        Set the log priority.

        :param int value: the log priority.
        """
        self._libudev.udev_set_log_priority(self, value)

    def list_devices(self, **kwargs):
        """
        List all available devices.

        The arguments of this method are the same as for
        :meth:`Enumerator.match()`.  In fact, the arguments are simply passed
        straight to method :meth:`~Enumerator.match()`.

        This function creates and returns an :class:`Enumerator` object,
        that can be used to filter the list of devices, and eventually
        retrieve :class:`Device` objects representing matching devices.

        .. versionchanged:: 0.8
           Accept keyword arguments now for easy matching.
        """
        return Enumerator(self).match(**kwargs)


class Enumerator(object):
    """
    A filtered iterable of devices.

    To retrieve devices, simply iterate over an instance of this class.
    This operation yields :class:`Device` objects representing the available
    devices.

    Before iteration the device list can be filtered by subsystem or by
    property values using :meth:`match_subsystem` and
    :meth:`match_property`.  Multiple subsystem (property) filters are
    combined using a logical OR, filters of different types are combined
    using a logical AND.  The following filter for instance::

        devices.match_subsystem('block').match_property(
            'ID_TYPE', 'disk').match_property('DEVTYPE', 'disk')

    means the following::

        subsystem == 'block' and (ID_TYPE == 'disk' or DEVTYPE == 'disk')

    Once added, a filter cannot be removed anymore.  Create a new object
    instead.

    Instances of this class can directly be given as given ``udev_enumerate *``
    to functions wrapped through :mod:`ctypes`.
    """

    def __init__(self, context):
        """
        Create a new enumerator with the given ``context`` (a
        :class:`Context` instance).

        While you can create objects of this class directly, this is not
        recommended.  Call :method:`Context.list_devices()` instead.
        """
        if not isinstance(context, Context):
            raise TypeError('Invalid context object')
        self.context = context
        self._as_parameter_ = context._libudev.udev_enumerate_new(context)
        self._libudev = context._libudev

    def __del__(self):
        self._libudev.udev_enumerate_unref(self)

    def match(self, **kwargs):
        """
        Include devices according to the rules defined by the keyword
        arguments.  These keyword arguments are interpreted as follows:

        - The value for the keyword argument ``subsystem`` is forwarded to
          :meth:`match_subsystem()`.
        - The value for the keyword argument ``sys_name`` is forwared to
          :meth:`match_sys_name()`.
        - The value for the keyword argument ``tag`` is forwared to
          :meth:`match_tag()`.
        - The value for the keyword argument ``parent`` is forwared to
          :meth:`match_parent()`.
        - All other keyword arguments are forwareded one by one to
          :meth:`match_property()`.  The keyword argument itself is interpreted
          as property name, the value of the keyword argument as the property
          value.

        All keyword arguments are optional, calling this method without no
        arguments at all is simply a noop.

        Return the instance again.

        .. versionadded:: 0.8

        .. versionchanged:: 0.13
           Add ``parent`` keyword.
        """
        subsystem = kwargs.pop('subsystem', None)
        if subsystem is not None:
            self.match_subsystem(subsystem)
        sys_name = kwargs.pop('sys_name', None)
        if sys_name is not None:
            self.match_sys_name(sys_name)
        tag = kwargs.pop('tag', None)
        if tag is not None:
            self.match_tag(tag)
        parent = kwargs.pop('parent', None)
        if parent is not None:
            self.match_parent(parent)
        for prop, value in kwargs.items():
            self.match_property(prop, value)
        return self

    def match_subsystem(self, subsystem, nomatch=False):
        """
        Include all devices, which are part of the given ``subsystem``.

        ``subsystem`` is either a unicode string or a byte string, containing
        the name of the subsystem.  If ``nomatch`` is ``True`` (default is
        ``False``), the match is inverted:  A device is only included if it is
        *not* part of the given ``subsystem``.

        Note that, if a device has no subsystem, it is not included either
        with value of ``nomatch`` True or with value of ``nomatch`` False.

        Return the instance again.
        """
        match = self._libudev.udev_enumerate_add_nomatch_subsystem \
           if nomatch else self._libudev.udev_enumerate_add_match_subsystem
        match(self, ensure_byte_string(subsystem))
        return self

    def match_sys_name(self, sys_name):
        """
        Include all devices with the given name.

        ``sys_name`` is a byte or unicode string containing the device name.

        Return the instance again.

        .. versionadded:: 0.8
        """
        self._libudev.udev_enumerate_add_match_sysname(
            self, ensure_byte_string(sys_name))
        return self

    def match_property(self, prop, value):
        """
        Include all devices, whose ``prop`` has the given ``value``.

        ``prop`` is either a unicode string or a byte string, containing
        the name of the property to match.  ``value`` is a property value,
        being one of the following types:

        - :func:`int`
        - :func:`bool`
        - A byte string
        - Anything convertable to a unicode string (including a unicode string
          itself)

        Return the instance again.
        """
        self._libudev.udev_enumerate_add_match_property(
            self, ensure_byte_string(prop), property_value_to_bytes(value))
        return self

    def match_attribute(self, attribute, value, nomatch=False):
        """
        Include all devices, whose ``attribute`` has the given ``value``.

        ``attribute`` is either a unicode string or a byte string, containing
        the name of a sys attribute to match.  ``value`` is an attribute value,
        being one of the following types:

        - :func:`int`,
        - :func:`bool`
        - A byte string
        - Anything convertable to a unicode string (including a unicode string
          itself)

        If ``nomatch`` is ``True`` (default is ``False``), the match is
        inverted:  A device is include if the ``attribute`` does *not* match
        the given ``value``.

        .. note::

           If ``nomatch`` is ``True``, devices which do not have the given
           ``attribute`` at all are also included.  In other words, with
           ``nomatch=True`` the given ``attribute`` is *not* guaranteed to
           exist on all returned devices.

        Return the instance again.
        """
        match = (self._libudev.udev_enumerate_add_match_sysattr
                 if not nomatch else
                 self._libudev.udev_enumerate_add_nomatch_sysattr)
        match(self, ensure_byte_string(attribute),
              property_value_to_bytes(value))
        return self

    def match_tag(self, tag):
        """
        Include all devices, which have the given ``tag`` attached.

        ``tag`` is a byte or unicode string containing the tag name.

        Return the instance again.

        .. udevversion:: 154

        .. versionadded:: 0.6
        """
        self._libudev.udev_enumerate_add_match_tag(self, ensure_byte_string(tag))
        return self

    def match_is_initialized(self):
        """
        Include only devices, which are initialized.

        Initialized devices have properly set device node permissions and
        context, and are (in case of network devices) fully renamed.

        Currently this will not affect devices which do not have device nodes
        and are not network interfaces.

        Return the instance again.

        .. seealso:: :attr:`Device.is_initialized`

        .. udevversion:: 165

        .. versionadded:: 0.8
        """
        self._libudev.udev_enumerate_add_match_is_initialized(self)
        return self

    def match_parent(self, parent):
        """
        Include all devices on the subtree of the given ``parent`` device.

        The ``parent`` device itself is also included.

        ``parent`` is a :class:`~pyudev.Device`.

        Return the instance again.

        .. udevversion:: 172

        .. versionadded:: 0.13
        """
        self._libudev.udev_enumerate_add_match_parent(self, parent)
        return self

    def __iter__(self):
        """
        Iterate over all matching devices.

        Yield :class:`Device` objects.
        """
        self._libudev.udev_enumerate_scan_devices(self)
        entry = self._libudev.udev_enumerate_get_list_entry(self)
        for name, _ in udev_list_iterate(self._libudev, entry):
            try:
                yield Devices.from_sys_path(self.context, name)
            except DeviceNotFoundAtPathError:
                continue
version.py000064400000002115150351420040006574 0ustar00# -*- coding: utf-8 -*-
# Copyright (C) 2015 mulhern <amulhern@redhat.com>

# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.

# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
# for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA


"""
    pyudev.version
    ==============

    Version information.

    .. moduleauthor::  mulhern  <amulhern@redhat.com>
"""

__version_info__ = (0, 21, 0, '')
__version__ = "%s%s" % \
   (
      ".".join(str(x) for x in __version_info__[:3]),
      "".join(str(x) for x in __version_info__[3:])
   )
_qt_base.py000064400000015553150351420040006676 0ustar00# -*- coding: utf-8 -*-
# Copyright (C) 2010, 2011, 2012, 2013 Sebastian Wiesner <lunaryorn@gmail.com>

# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.

# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
# for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA


"""
    pyudev._qt_base
    ===============

    Base mixin class for Qt4,Qt5 support.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import six

from pyudev.device import Device

class MonitorObserverMixin(object):
    """
    Base mixin for pyqt monitor observers.
    """
    # pylint: disable=too-few-public-methods

    def _setup_notifier(self, monitor, notifier_class):
        self.monitor = monitor
        self.notifier = notifier_class(
            monitor.fileno(), notifier_class.Read, self)
        self.notifier.activated[int].connect(self._process_udev_event)

    @property
    def enabled(self):
        """
        Whether this observer is enabled or not.

        If ``True`` (the default), this observer is enabled, and emits events.
        Otherwise it is disabled and does not emit any events.  This merely
        reflects the state of the ``enabled`` property of the underlying
        :attr:`notifier`.

        .. versionadded:: 0.14
        """
        return self.notifier.isEnabled()

    @enabled.setter
    def enabled(self, value):
        self.notifier.setEnabled(value)

    def _process_udev_event(self):
        """
        Attempt to receive a single device event from the monitor, process
        the event and emit corresponding signals.

        Called by ``QSocketNotifier``, if data is available on the udev
        monitoring socket.
        """
        device = self.monitor.poll(timeout=0)
        if device is not None:
            self._emit_event(device)

    def _emit_event(self, device):
        self.deviceEvent.emit(device)


class QUDevMonitorObserverMixin(MonitorObserverMixin):
    """
    Obsolete monitor observer mixin.
    """
    # pylint: disable=too-few-public-methods

    def _setup_notifier(self, monitor, notifier_class):
        MonitorObserverMixin._setup_notifier(self, monitor, notifier_class)
        self._action_signal_map = {
            'add': self.deviceAdded, 'remove': self.deviceRemoved,
            'change': self.deviceChanged, 'move': self.deviceMoved,
        }
        import warnings
        warnings.warn('Will be removed in 1.0. '
                      'Use pyudev.pyqt4.MonitorObserver instead.',
                      DeprecationWarning)

    def _emit_event(self, device):
        self.deviceEvent.emit(device.action, device)
        signal = self._action_signal_map.get(device.action)
        if signal is not None:
            signal.emit(device)

def make_init(qobject, socket_notifier):
    """
    Generates an initializer to observer the given ``monitor``
    (a :class:`~pyudev.Monitor`):

    ``parent`` is the parent :class:`~PyQt{4,5}.QtCore.QObject` of this
    object.  It is passed unchanged to the inherited constructor of
    :class:`~PyQt{4,5}.QtCore.QObject`.
    """

    def __init__(self, monitor, parent=None):
        qobject.__init__(self, parent)
        # pylint: disable=protected-access
        self._setup_notifier(monitor, socket_notifier)

    return __init__


class MonitorObserverGenerator(object):
    """
    Class to generate a MonitorObserver class.
    """
    # pylint: disable=too-few-public-methods

    @staticmethod
    def make_monitor_observer(qobject, signal, socket_notifier):
        """Generates an observer for device events integrating into the
        PyQt{4,5} mainloop.

        This class inherits :class:`~PyQt{4,5}.QtCore.QObject` to turn device
        events into Qt signals:

        >>> from pyudev import Context, Monitor
        >>> from pyudev.pyqt4 import MonitorObserver
        >>> context = Context()
        >>> monitor = Monitor.from_netlink(context)
        >>> monitor.filter_by(subsystem='input')
        >>> observer = MonitorObserver(monitor)
        >>> def device_event(device):
        ...     print('event {0} on device {1}'.format(device.action, device))
        >>> observer.deviceEvent.connect(device_event)
        >>> monitor.start()

        This class is a child of :class:`~{PySide, PyQt{4,5}}.QtCore.QObject`.

        """
        return type(
           str("MonitorObserver"),
           (qobject, MonitorObserverMixin),
           {
              str("__init__") : make_init(qobject, socket_notifier),
              str("deviceEvent") : signal(Device)
           }
        )



class QUDevMonitorObserverGenerator(object):
    """
    Class to generate a MonitorObserver class.
    """
    # pylint: disable=too-few-public-methods

    @staticmethod
    def make_monitor_observer(qobject, signal, socket_notifier):
        """Generates an observer for device events integrating into the
        PyQt{4,5} mainloop.

        This class inherits :class:`~PyQt{4,5}.QtCore.QObject` to turn device
        events into Qt signals:

        >>> from pyudev import Context, Monitor
        >>> from pyudev.pyqt4 import MonitorObserver
        >>> context = Context()
        >>> monitor = Monitor.from_netlink(context)
        >>> monitor.filter_by(subsystem='input')
        >>> observer = MonitorObserver(monitor)
        >>> def device_event(device):
        ...     print('event {0} on device {1}'.format(device.action, device))
        >>> observer.deviceEvent.connect(device_event)
        >>> monitor.start()

        This class is a child of :class:`~{PyQt{4,5}, PySide}.QtCore.QObject`.

        """
        return type(
           str("QUDevMonitorObserver"),
           (qobject, QUDevMonitorObserverMixin),
           {
              str("__init__") : make_init(qobject, socket_notifier),
              #: emitted upon arbitrary device events
              str("deviceEvent") : signal(six.text_type, Device),
              #: emitted if a device was added
              str("deviceAdded") : signal(Device),
              #: emitted if a device was removed
              str("deviceRemoved") : signal(Device),
              #: emitted if a device was changed
              str("deviceChanged") : signal(Device),
              #: emitted if a device was moved
              str("deviceMoved") : signal(Device)
           }
        )
_os/__init__.py000064400000001741150351420040007432 0ustar00# -*- coding: utf-8 -*-
# Copyright (C) 2015 mulhern <amulhern@redhat.com>

# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.

# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
# for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

"""
    pyudev._os
    ==========

    Extras to compensate for deficiencies in python os module.

    .. moduleauthor::  mulhern  <amulhern@redhat.com>
"""

from . import pipe
from . import poll
_os/pipe.py000064400000010703150351420040006626 0ustar00# -*- coding: utf-8 -*-
# Copyright (C) 2013 Sebastian Wiesner <lunaryorn@gmail.com>

# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.

# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
# for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA


"""
    pyudev._os.pipe
    ===============

    Fallback implementations for pipe.

    1. pipe2 from python os module
    2. pipe2 from libc
    3. pipe from python os module

    The Pipe class wraps the chosen implementation.

    .. moduleauthor:: Sebastian Wiesner  <lunaryorn@gmail.com>
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import os
import fcntl
from functools import partial

from pyudev._ctypeslib.libc import fd_pair
from pyudev._ctypeslib.libc import ERROR_CHECKERS
from pyudev._ctypeslib.libc import SIGNATURES
from pyudev._ctypeslib.utils import load_ctypes_library

# Define O_CLOEXEC, if not present in os already
O_CLOEXEC = getattr(os, 'O_CLOEXEC', 0o2000000)


def _pipe2_ctypes(libc, flags):
    """A ``pipe2`` implementation using ``pipe2`` from ctypes.

    ``libc`` is a :class:`ctypes.CDLL` object for libc.  ``flags`` is an
    integer providing the flags to ``pipe2``.

    Return a pair of file descriptors ``(r, w)``.

    """
    fds = fd_pair()
    libc.pipe2(fds, flags)
    return fds[0], fds[1]


def _pipe2_by_pipe(flags):
    """A ``pipe2`` implementation using :func:`os.pipe`.

    ``flags`` is an integer providing the flags to ``pipe2``.

    .. warning::

       This implementation is not atomic!

    Return a pair of file descriptors ``(r, w)``.

    """
    fds = os.pipe()
    if flags & os.O_NONBLOCK != 0:
        for fd in fds:
            set_fd_status_flag(fd, os.O_NONBLOCK)
    if flags & O_CLOEXEC != 0:
        for fd in fds:
            set_fd_flag(fd, O_CLOEXEC)
    return fds


def _get_pipe2_implementation():
    """Find the appropriate implementation for ``pipe2``.

Return a function implementing ``pipe2``."""
    if hasattr(os, 'pipe2'):
        return os.pipe2 # pylint: disable=no-member
    else:
        try:
            libc = load_ctypes_library("libc", SIGNATURES, ERROR_CHECKERS)
            return (partial(_pipe2_ctypes, libc)
                    if hasattr(libc, 'pipe2') else
                    _pipe2_by_pipe)
        except ImportError:
            return _pipe2_by_pipe


_PIPE2 = _get_pipe2_implementation()


def set_fd_flag(fd, flag):
    """Set a flag on a file descriptor.

    ``fd`` is the file descriptor or file object, ``flag`` the flag as integer.

    """
    flags = fcntl.fcntl(fd, fcntl.F_GETFD, 0)
    fcntl.fcntl(fd, fcntl.F_SETFD, flags | flag)


def set_fd_status_flag(fd, flag):
    """Set a status flag on a file descriptor.

    ``fd`` is the file descriptor or file object, ``flag`` the flag as integer.

    """
    flags = fcntl.fcntl(fd, fcntl.F_GETFL, 0)
    fcntl.fcntl(fd, fcntl.F_SETFL, flags | flag)


class Pipe(object):
    """A unix pipe.

    A pipe object provides two file objects: :attr:`source` is a readable file
    object, and :attr:`sink` a writeable.  Bytes written to :attr:`sink` appear
    at :attr:`source`.

    Open a pipe with :meth:`open()`.

    """

    @classmethod
    def open(cls):
        """Open and return a new :class:`Pipe`.

        The pipe uses non-blocking IO."""
        source, sink = _PIPE2(os.O_NONBLOCK | O_CLOEXEC)
        return cls(source, sink)

    def __init__(self, source_fd, sink_fd):
        """Create a new pipe object from the given file descriptors.

        ``source_fd`` is a file descriptor for the readable side of the pipe,
        ``sink_fd`` is a file descriptor for the writeable side."""
        self.source = os.fdopen(source_fd, 'rb', 0)
        self.sink = os.fdopen(sink_fd, 'wb', 0)

    def close(self):
        """Closes both sides of the pipe."""
        try:
            self.source.close()
        finally:
            self.sink.close()
_os/__pycache__/pipe.cpython-36.pyc000064400000007657150351420040013130 0ustar003

u1�W��@s�dZddlmZddlmZddlmZddlmZddlZddlZddlm	Z	ddl
mZdd	l
mZdd
l
m
Z
ddlmZeedd
�Zdd�Zdd�Zdd�Ze�Zdd�Zdd�ZGdd�de�ZdS)a#
    pyudev._os.pipe
    ===============

    Fallback implementations for pipe.

    1. pipe2 from python os module
    2. pipe2 from libc
    3. pipe from python os module

    The Pipe class wraps the chosen implementation.

    .. moduleauthor:: Sebastian Wiesner  <lunaryorn@gmail.com>
�)�absolute_import)�division)�print_function)�unicode_literalsN)�partial)�fd_pair)�ERROR_CHECKERS)�
SIGNATURES)�load_ctypes_library�	O_CLOEXECicCs"t�}|j||�|d|dfS)z�A ``pipe2`` implementation using ``pipe2`` from ctypes.

    ``libc`` is a :class:`ctypes.CDLL` object for libc.  ``flags`` is an
    integer providing the flags to ``pipe2``.

    Return a pair of file descriptors ``(r, w)``.

    r�)r�pipe2)�libc�flags�fds�r�/usr/lib/python3.6/pipe.py�
_pipe2_ctypes4s	rcCsXtj�}|tj@dkr0x|D]}t|tj�qW|t@dkrTx|D]}t|t�qBW|S)z�A ``pipe2`` implementation using :func:`os.pipe`.

    ``flags`` is an integer providing the flags to ``pipe2``.

    .. warning::

       This implementation is not atomic!

    Return a pair of file descriptors ``(r, w)``.

    r)�os�pipe�
O_NONBLOCK�set_fd_status_flagr�set_fd_flag)rr�fdrrr�_pipe2_by_pipeBs

rcCsNttd�rtjSy$tdtt�}t|d�r2tt|�StSt	k
rHtSXdS)z]Find the appropriate implementation for ``pipe2``.

Return a function implementing ``pipe2``.r
rN)
�hasattrrr
r
r	rrrr�ImportError)rrrr�_get_pipe2_implementationXs
rcCs(tj|tjd�}tj|tj||B�dS)zwSet a flag on a file descriptor.

    ``fd`` is the file descriptor or file object, ``flag`` the flag as integer.

    rN)�fcntlZF_GETFDZF_SETFD)r�flagrrrrrksrcCs(tj|tjd�}tj|tj||B�dS)z~Set a status flag on a file descriptor.

    ``fd`` is the file descriptor or file object, ``flag`` the flag as integer.

    rN)rZF_GETFLZF_SETFL)rrrrrrrusrc@s,eZdZdZedd��Zdd�Zdd�ZdS)	�Pipez�A unix pipe.

    A pipe object provides two file objects: :attr:`source` is a readable file
    object, and :attr:`sink` a writeable.  Bytes written to :attr:`sink` appear
    at :attr:`source`.

    Open a pipe with :meth:`open()`.

    cCsttjtB�\}}|||�S)zLOpen and return a new :class:`Pipe`.

        The pipe uses non-blocking IO.)�_PIPE2rrr)�cls�source�sinkrrr�open�sz	Pipe.opencCs$tj|dd�|_tj|dd�|_dS)z�Create a new pipe object from the given file descriptors.

        ``source_fd`` is a file descriptor for the readable side of the pipe,
        ``sink_fd`` is a file descriptor for the writeable side.�rbr�wbN)r�fdopenr#r$)�selfZ	source_fdZsink_fdrrr�__init__�sz
Pipe.__init__c
Cs z|jj�Wd|jj�XdS)zCloses both sides of the pipe.N)r#�closer$)r)rrrr+�sz
Pipe.closeN)�__name__�
__module__�__qualname__�__doc__�classmethodr%r*r+rrrrr s	r )r/Z
__future__rrrrrr�	functoolsrZpyudev._ctypeslib.libcrrr	Zpyudev._ctypeslib.utilsr
�getattrrrrrr!rr�objectr rrrr�<module> s&

_os/__pycache__/pipe.cpython-36.opt-1.pyc000064400000007657150351420040014067 0ustar003

u1�W��@s�dZddlmZddlmZddlmZddlmZddlZddlZddlm	Z	ddl
mZdd	l
mZdd
l
m
Z
ddlmZeedd
�Zdd�Zdd�Zdd�Ze�Zdd�Zdd�ZGdd�de�ZdS)a#
    pyudev._os.pipe
    ===============

    Fallback implementations for pipe.

    1. pipe2 from python os module
    2. pipe2 from libc
    3. pipe from python os module

    The Pipe class wraps the chosen implementation.

    .. moduleauthor:: Sebastian Wiesner  <lunaryorn@gmail.com>
�)�absolute_import)�division)�print_function)�unicode_literalsN)�partial)�fd_pair)�ERROR_CHECKERS)�
SIGNATURES)�load_ctypes_library�	O_CLOEXECicCs"t�}|j||�|d|dfS)z�A ``pipe2`` implementation using ``pipe2`` from ctypes.

    ``libc`` is a :class:`ctypes.CDLL` object for libc.  ``flags`` is an
    integer providing the flags to ``pipe2``.

    Return a pair of file descriptors ``(r, w)``.

    r�)r�pipe2)�libc�flags�fds�r�/usr/lib/python3.6/pipe.py�
_pipe2_ctypes4s	rcCsXtj�}|tj@dkr0x|D]}t|tj�qW|t@dkrTx|D]}t|t�qBW|S)z�A ``pipe2`` implementation using :func:`os.pipe`.

    ``flags`` is an integer providing the flags to ``pipe2``.

    .. warning::

       This implementation is not atomic!

    Return a pair of file descriptors ``(r, w)``.

    r)�os�pipe�
O_NONBLOCK�set_fd_status_flagr�set_fd_flag)rr�fdrrr�_pipe2_by_pipeBs

rcCsNttd�rtjSy$tdtt�}t|d�r2tt|�StSt	k
rHtSXdS)z]Find the appropriate implementation for ``pipe2``.

Return a function implementing ``pipe2``.r
rN)
�hasattrrr
r
r	rrrr�ImportError)rrrr�_get_pipe2_implementationXs
rcCs(tj|tjd�}tj|tj||B�dS)zwSet a flag on a file descriptor.

    ``fd`` is the file descriptor or file object, ``flag`` the flag as integer.

    rN)�fcntlZF_GETFDZF_SETFD)r�flagrrrrrksrcCs(tj|tjd�}tj|tj||B�dS)z~Set a status flag on a file descriptor.

    ``fd`` is the file descriptor or file object, ``flag`` the flag as integer.

    rN)rZF_GETFLZF_SETFL)rrrrrrrusrc@s,eZdZdZedd��Zdd�Zdd�ZdS)	�Pipez�A unix pipe.

    A pipe object provides two file objects: :attr:`source` is a readable file
    object, and :attr:`sink` a writeable.  Bytes written to :attr:`sink` appear
    at :attr:`source`.

    Open a pipe with :meth:`open()`.

    cCsttjtB�\}}|||�S)zLOpen and return a new :class:`Pipe`.

        The pipe uses non-blocking IO.)�_PIPE2rrr)�cls�source�sinkrrr�open�sz	Pipe.opencCs$tj|dd�|_tj|dd�|_dS)z�Create a new pipe object from the given file descriptors.

        ``source_fd`` is a file descriptor for the readable side of the pipe,
        ``sink_fd`` is a file descriptor for the writeable side.�rbr�wbN)r�fdopenr#r$)�selfZ	source_fdZsink_fdrrr�__init__�sz
Pipe.__init__c
Cs z|jj�Wd|jj�XdS)zCloses both sides of the pipe.N)r#�closer$)r)rrrr+�sz
Pipe.closeN)�__name__�
__module__�__qualname__�__doc__�classmethodr%r*r+rrrrr s	r )r/Z
__future__rrrrrr�	functoolsrZpyudev._ctypeslib.libcrrr	Zpyudev._ctypeslib.utilsr
�getattrrrrrr!rr�objectr rrrr�<module> s&

_os/__pycache__/poll.cpython-36.pyc000064400000006434150351420040013131 0ustar003

�W�@s\dZddlmZddlmZddlmZddlmZddlZddlmZGdd	�d	e	�Z
dS)
z�
    pyudev._os.poll
    ===============

    Operating system interface for pyudev.

    .. moduleauthor:: Sebastian Wiesner  <lunaryorn@gmail.com>
�)�absolute_import)�division)�print_function)�unicode_literalsN)�eintr_retry_callc@sPeZdZdZejejd�Zedd��Z	e
dd��Zdd�Zdd
d�Z
dd
�Zd	S)�PollzwA poll object.

    This object essentially provides a more convenient interface around
    :class:`select.poll`.

    )�r�wcCs||@dkS)Nr�)�events�eventr
r
�/usr/lib/python3.6/poll.py�
_has_event1szPoll._has_eventcGsNttj�}x:|D]2\}}|jj|�}|s6tdj|���|j||�qW||�S)aGListen for ``events``.

        ``events`` is a list of ``(fd, event)`` pairs, where ``fd`` is a file
        descriptor or file object and ``event`` either ``'r'`` or ``'w'``.  If
        ``r``, listen for whether that is ready to be read.  If ``w``, listen
        for whether the channel is ready to be written to.

        zUnknown event type: {0!r})r�select�poll�_EVENT_TO_MASK�get�
ValueError�format�register)�clsr�notifier�fdr�maskr
r
r
�
for_events5s

zPoll.for_eventscCs
||_dS)z�Create a poll object for the given ``notifier``.

        ``notifier`` is the :class:`select.poll` object wrapped by the new poll
        object.

        N)�	_notifier)�selfrr
r
r
�__init__Gsz
Poll.__init__NcCst|jt|jj|���S)a{Poll for events.

        ``timeout`` is an integer specifying how long to wait for events (in
        milliseconds).  If omitted, ``None`` or negative, wait until an event
        occurs.

        Return a list of all events that occurred before ``timeout``, where
        each event is a pair ``(fd, event)``. ``fd`` is the integral file
        descriptor, and ``event`` a string indicating the event type.  If
        ``'r'``, there is data to read from ``fd``.  If ``'w'``, ``fd`` is
        writable without blocking now.  If ``'h'``, the file descriptor was
        hung up (i.e. the remote side of a pipe was closed).

        )�list�
_parse_eventsrrr)rZtimeoutr
r
r
rPsz	Poll.pollccs�x�|D]�\}}|j|tj�r,tdj|���n|j|tj�rHtdj|���|j|tj�r`|dfV|j|tj�rx|dfV|j|tj�r|dfVqWdS)z�Parse ``events``.

        ``events`` is a list of events as returned by
        :meth:`select.poll.poll()`.

        Yield all parsed events.

        zFile descriptor not open: {0!r}zError while polling fd: {0!r}rr	�hN)	rrZPOLLNVAL�IOErrorrZPOLLERR�POLLIN�POLLOUTZPOLLHUP)rrrZ
event_maskr
r
r
rcs	

zPoll._parse_events)N)�__name__�
__module__�__qualname__�__doc__rr"r#r�staticmethodr�classmethodrrrrr
r
r
r
r&s
	
r)r'Z
__future__rrrrrZpyudev._utilr�objectrr
r
r
r
�<module>s_os/__pycache__/poll.cpython-36.opt-1.pyc000064400000006434150351420040014070 0ustar003

�W�@s\dZddlmZddlmZddlmZddlmZddlZddlmZGdd	�d	e	�Z
dS)
z�
    pyudev._os.poll
    ===============

    Operating system interface for pyudev.

    .. moduleauthor:: Sebastian Wiesner  <lunaryorn@gmail.com>
�)�absolute_import)�division)�print_function)�unicode_literalsN)�eintr_retry_callc@sPeZdZdZejejd�Zedd��Z	e
dd��Zdd�Zdd
d�Z
dd
�Zd	S)�PollzwA poll object.

    This object essentially provides a more convenient interface around
    :class:`select.poll`.

    )�r�wcCs||@dkS)Nr�)�events�eventr
r
�/usr/lib/python3.6/poll.py�
_has_event1szPoll._has_eventcGsNttj�}x:|D]2\}}|jj|�}|s6tdj|���|j||�qW||�S)aGListen for ``events``.

        ``events`` is a list of ``(fd, event)`` pairs, where ``fd`` is a file
        descriptor or file object and ``event`` either ``'r'`` or ``'w'``.  If
        ``r``, listen for whether that is ready to be read.  If ``w``, listen
        for whether the channel is ready to be written to.

        zUnknown event type: {0!r})r�select�poll�_EVENT_TO_MASK�get�
ValueError�format�register)�clsr�notifier�fdr�maskr
r
r
�
for_events5s

zPoll.for_eventscCs
||_dS)z�Create a poll object for the given ``notifier``.

        ``notifier`` is the :class:`select.poll` object wrapped by the new poll
        object.

        N)�	_notifier)�selfrr
r
r
�__init__Gsz
Poll.__init__NcCst|jt|jj|���S)a{Poll for events.

        ``timeout`` is an integer specifying how long to wait for events (in
        milliseconds).  If omitted, ``None`` or negative, wait until an event
        occurs.

        Return a list of all events that occurred before ``timeout``, where
        each event is a pair ``(fd, event)``. ``fd`` is the integral file
        descriptor, and ``event`` a string indicating the event type.  If
        ``'r'``, there is data to read from ``fd``.  If ``'w'``, ``fd`` is
        writable without blocking now.  If ``'h'``, the file descriptor was
        hung up (i.e. the remote side of a pipe was closed).

        )�list�
_parse_eventsrrr)rZtimeoutr
r
r
rPsz	Poll.pollccs�x�|D]�\}}|j|tj�r,tdj|���n|j|tj�rHtdj|���|j|tj�r`|dfV|j|tj�rx|dfV|j|tj�r|dfVqWdS)z�Parse ``events``.

        ``events`` is a list of events as returned by
        :meth:`select.poll.poll()`.

        Yield all parsed events.

        zFile descriptor not open: {0!r}zError while polling fd: {0!r}rr	�hN)	rrZPOLLNVAL�IOErrorrZPOLLERR�POLLIN�POLLOUTZPOLLHUP)rrrZ
event_maskr
r
r
rcs	

zPoll._parse_events)N)�__name__�
__module__�__qualname__�__doc__rr"r#r�staticmethodr�classmethodrrrrr
r
r
r
r&s
	
r)r'Z
__future__rrrrrZpyudev._utilr�objectrr
r
r
r
�<module>s_os/__pycache__/__init__.cpython-36.pyc000064400000000520150351420040013710 0ustar003

H�V��@s dZddlmZddlmZdS)z�
    pyudev._os
    ==========

    Extras to compensate for deficiencies in python os module.

    .. moduleauthor::  mulhern  <amulhern@redhat.com>
�)�pipe)�pollN)�__doc__�rr�rr�/usr/lib/python3.6/__init__.py�<module>s_os/__pycache__/__init__.cpython-36.opt-1.pyc000064400000000520150351420040014647 0ustar003

H�V��@s dZddlmZddlmZdS)z�
    pyudev._os
    ==========

    Extras to compensate for deficiencies in python os module.

    .. moduleauthor::  mulhern  <amulhern@redhat.com>
�)�pipe)�pollN)�__doc__�rr�rr�/usr/lib/python3.6/__init__.py�<module>s_os/poll.py000064400000010033150351420040006633 0ustar00# -*- coding: utf-8 -*-
# Copyright (C) 2013 Sebastian Wiesner <lunaryorn@gmail.com>

# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.

# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
# for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA


"""
    pyudev._os.poll
    ===============

    Operating system interface for pyudev.

    .. moduleauthor:: Sebastian Wiesner  <lunaryorn@gmail.com>
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import select

from pyudev._util import eintr_retry_call


class Poll(object):
    """A poll object.

    This object essentially provides a more convenient interface around
    :class:`select.poll`.

    """

    _EVENT_TO_MASK = {'r': select.POLLIN,
                      'w': select.POLLOUT}

    @staticmethod
    def _has_event(events, event):
        return events & event != 0

    @classmethod
    def for_events(cls, *events):
        """Listen for ``events``.

        ``events`` is a list of ``(fd, event)`` pairs, where ``fd`` is a file
        descriptor or file object and ``event`` either ``'r'`` or ``'w'``.  If
        ``r``, listen for whether that is ready to be read.  If ``w``, listen
        for whether the channel is ready to be written to.

        """
        notifier = eintr_retry_call(select.poll)
        for fd, event in events:
            mask = cls._EVENT_TO_MASK.get(event)
            if not mask:
                raise ValueError('Unknown event type: {0!r}'.format(event))
            notifier.register(fd, mask)
        return cls(notifier)

    def __init__(self, notifier):
        """Create a poll object for the given ``notifier``.

        ``notifier`` is the :class:`select.poll` object wrapped by the new poll
        object.

        """
        self._notifier = notifier

    def poll(self, timeout=None):
        """Poll for events.

        ``timeout`` is an integer specifying how long to wait for events (in
        milliseconds).  If omitted, ``None`` or negative, wait until an event
        occurs.

        Return a list of all events that occurred before ``timeout``, where
        each event is a pair ``(fd, event)``. ``fd`` is the integral file
        descriptor, and ``event`` a string indicating the event type.  If
        ``'r'``, there is data to read from ``fd``.  If ``'w'``, ``fd`` is
        writable without blocking now.  If ``'h'``, the file descriptor was
        hung up (i.e. the remote side of a pipe was closed).

        """
        # Return a list to allow clients to determine whether there are any
        # events at all with a simple truthiness test.
        return list(self._parse_events(eintr_retry_call(self._notifier.poll, timeout)))

    def _parse_events(self, events):
        """Parse ``events``.

        ``events`` is a list of events as returned by
        :meth:`select.poll.poll()`.

        Yield all parsed events.

        """
        for fd, event_mask in events:
            if self._has_event(event_mask, select.POLLNVAL):
                raise IOError('File descriptor not open: {0!r}'.format(fd))
            elif self._has_event(event_mask, select.POLLERR):
                raise IOError('Error while polling fd: {0!r}'.format(fd))

            if self._has_event(event_mask, select.POLLIN):
                yield fd, 'r'
            if self._has_event(event_mask, select.POLLOUT):
                yield fd, 'w'
            if self._has_event(event_mask, select.POLLHUP):
                yield fd, 'h'
device/__init__.py000064400000002517150351420040010113 0ustar00# -*- coding: utf-8 -*-
# Copyright (C) 2015 mulhern <amulhern@redhat.com>

# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.

# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
# for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

"""
    pyudev.device
    =============

    Device class implementation of :mod:`pyudev`.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
"""


from ._device import Attributes
from ._device import Device
from ._device import Devices
from ._device import Tags
from ._errors import DeviceNotFoundAtPathError
from ._errors import DeviceNotFoundByFileError
from ._errors import DeviceNotFoundByNameError
from ._errors import DeviceNotFoundByNumberError
from ._errors import DeviceNotFoundError
from ._errors import DeviceNotFoundInEnvironmentError
device/_errors.py000064400000012154150351420040010025 0ustar00# -*- coding: utf-8 -*-
# Copyright (C) 2015 mulhern <amulhern@redhat.com>

# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.

# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
# for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA

"""
    pyudev.device._errors
    =====================

    Errors raised by Device methods.

    .. moduleauthor:: Sebastian Wiesner <lunaryorn@gmail.com>
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import abc

from six import add_metaclass

@add_metaclass(abc.ABCMeta)
class DeviceError(Exception):
    """
    Any error raised when messing around w/ or trying to discover devices.
    """


@add_metaclass(abc.ABCMeta)
class DeviceNotFoundError(DeviceError):
    """
    An exception indicating that no :class:`Device` was found.

    .. versionchanged:: 0.5
       Rename from ``NoSuchDeviceError`` to its current name.
    """


class DeviceNotFoundAtPathError(DeviceNotFoundError):
    """
    A :exc:`DeviceNotFoundError` indicating that no :class:`Device` was
    found at a given path.
    """

    def __init__(self, sys_path):
        DeviceNotFoundError.__init__(self, sys_path)

    @property
    def sys_path(self):
        """
        The path that caused this error as string.
        """
        return self.args[0]

    def __str__(self):
        return 'No device at {0!r}'.format(self.sys_path)


class DeviceNotFoundByFileError(DeviceNotFoundError):
    """
    A :exc:`DeviceNotFoundError` indicating that no :class:`Device` was
    found from the given filename.
    """

class DeviceNotFoundByInterfaceIndexError(DeviceNotFoundError):
    """
    A :exc:`DeviceNotFoundError` indicating that no :class:`Device` was found
    from the given interface index.
    """

class DeviceNotFoundByKernelDeviceError(DeviceNotFoundError):
    """
    A :exc:`DeviceNotFoundError` indicating that no :class:`Device` was found
    from the given kernel device string.

    The format of the kernel device string is defined in the
    systemd.journal-fields man pagees.
    """


class DeviceNotFoundByNameError(DeviceNotFoundError):
    """
    A :exc:`DeviceNotFoundError` indicating that no :class:`Device` was
    found with a given name.
    """

    def __init__(self, subsystem, sys_name):
        DeviceNotFoundError.__init__(self, subsystem, sys_name)

    @property
    def subsystem(self):
        """
        The subsystem that caused this error as string.
        """
        return self.args[0]

    @property
    def sys_name(self):
        """
        The sys name that caused this error as string.
        """
        return self.args[1]

    def __str__(self):
        return 'No device {0.sys_name!r} in {0.subsystem!r}'.format(self)


class DeviceNotFoundByNumberError(DeviceNotFoundError):
    """
    A :exc:`DeviceNotFoundError` indicating, that no :class:`Device` was found
    for a given device number.
    """

    def __init__(self, typ, number):
        DeviceNotFoundError.__init__(self, typ, number)

    @property
    def device_type(self):
        """
        The device type causing this error as string.  Either ``'char'`` or
        ``'block'``.
        """
        return self.args[0]

    @property
    def device_number(self):
        """
        The device number causing this error as integer.
        """
        return self.args[1]

    def __str__(self):
        return ('No {0.device_type} device with number '
                '{0.device_number}'.format(self))


class DeviceNotFoundInEnvironmentError(DeviceNotFoundError):
    """
    A :exc:`DeviceNotFoundError` indicating, that no :class:`Device` could
    be constructed from the process environment.
    """

    def __str__(self):
        return 'No device found in environment'


class DeviceValueError(DeviceError):
    """
    Raised when a parameter has an unacceptable value.

    May also be raised when the parameter has an unacceptable type.
    """

    _FMT_STR = "value '%s' for parameter %s is unacceptable"

    def __init__(self, value, param, msg=None):
        """ Initializer.

            :param object value: the value
            :param str param: the parameter
            :param str msg: an explanatory message
        """
        # pylint: disable=super-init-not-called
        self._value = value
        self._param = param
        self._msg = msg

    def __str__(self):
        if self._msg:
            fmt_str = self._FMT_STR + ": %s"
            return fmt_str % (self._value, self._param, self._msg)
        else:
            return self._FMT_STR % (self._value, self._param)
device/__pycache__/_device.cpython-36.opt-1.pyc000064400000124641150351420040015200 0ustar003

u1�Wɭ�@sZdZddlmZddlmZddlmZddlmZddlZddlZddlm	Z	ddlm
Z
dd	lmZdd
lm
Z
ddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�Z Gdd �d e
e	�Z!dS)!z�
    pyudev.device._device
    =====================

    Device class implementation of :mod:`pyudev`.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
�)�absolute_import)�division)�print_function)�unicode_literalsN)�	Container)�Iterable)�Mapping)�	timedelta)�DeviceNotFoundAtPathError)�DeviceNotFoundByFileError)�#DeviceNotFoundByInterfaceIndexError)�!DeviceNotFoundByKernelDeviceError)�DeviceNotFoundByNameError)�DeviceNotFoundByNumberError)� DeviceNotFoundInEnvironmentError)�ensure_byte_string)�ensure_unicode_string)�get_device_type)�string_to_bool)�udev_list_iteratec@s|eZdZdZedd��Zedd��Zedd��Zedd	��Zed
d��Z	edd
��Z
edd��Zedd��Zedd��Z
dS)�DeviceszT
    Class for constructing :class:`Device` objects from various kinds of data.
    cCs0|j|j�s$tjj|j|jtj��}|j||�S)a�
        Create a device from a device ``path``.  The ``path`` may or may not
        start with the ``sysfs`` mount point:

        >>> from pyudev import Context, Device
        >>> context = Context()
        >>> Devices.from_path(context, '/devices/platform')
        Device(u'/sys/devices/platform')
        >>> Devices.from_path(context, '/sys/devices/platform')
        Device(u'/sys/devices/platform')

        ``context`` is the :class:`Context` in which to search the device.
        ``path`` is a device path as unicode or byte string.

        Return a :class:`Device` object for the device.  Raise
        :exc:`DeviceNotFoundAtPathError`, if no device was found for ``path``.

        .. versionadded:: 0.18
        )�
startswith�sys_path�os�path�join�lstrip�sep�
from_sys_path)�cls�contextr�r!�/usr/lib/python3.6/_device.py�	from_path<szDevices.from_pathcCs(|jj|t|��}|st|��t||�S)a�
        Create a new device from a given ``sys_path``:

        >>> from pyudev import Context, Device
        >>> context = Context()
        >>> Devices.from_sys_path(context, '/sys/devices/platform')
        Device(u'/sys/devices/platform')

        ``context`` is the :class:`Context` in which to search the device.
        ``sys_path`` is a unicode or byte string containing the path of the
        device inside ``sysfs`` with the mount point included.

        Return a :class:`Device` object for the device.  Raise
        :exc:`DeviceNotFoundAtPathError`, if no device was found for
        ``sys_path``.

        .. versionadded:: 0.18
        )�_libudevZudev_device_new_from_syspathrr
�Device)rr r�devicer!r!r"rUs
zDevices.from_sys_pathcCs<|jdd�}|jj|t|�t|��}|s2t||��t||�S)a.
        Create a new device from a given ``subsystem`` and a given
        ``sys_name``:

        >>> from pyudev import Context, Device
        >>> context = Context()
        >>> sda = Devices.from_name(context, 'block', 'sda')
        >>> sda
        Device(u'/sys/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda')
        >>> sda == Devices.from_path(context, '/block/sda')

        ``context`` is the :class:`Context` in which to search the device.
        ``subsystem`` and ``sys_name`` are byte or unicode strings, which
        denote the subsystem and the name of the device to create.

        Return a :class:`Device` object for the device.  Raise
        :exc:`DeviceNotFoundByNameError`, if no device was found with the given
        name.

        .. versionadded:: 0.18
        �/�!)�replacer$Z&udev_device_new_from_subsystem_sysnamerrr%)rr �	subsystem�sys_namer&r!r!r"�	from_nameos

zDevices.from_namecCs0|jj|t|d�|�}|s&t||��t||�S)a�
        Create a new device from a device ``number`` with the given device
        ``type``:

        >>> import os
        >>> from pyudev import Context, Device
        >>> ctx = Context()
        >>> major, minor = 8, 0
        >>> device = Devices.from_device_number(context, 'block',
        ...     os.makedev(major, minor))
        >>> device
        Device(u'/sys/devices/pci0000:00/0000:00:11.0/host0/target0:0:0/0:0:0:0/block/sda')
        >>> os.major(device.device_number), os.minor(device.device_number)
        (8, 0)

        Use :func:`os.makedev` to construct a device number from a major and a
        minor device number, as shown in the example above.

        .. warning::

           Device numbers are not unique across different device types.
           Passing a correct number with a wrong type may silently yield a
           wrong device object, so make sure to pass the correct device type.

        ``context`` is the :class:`Context`, in which to search the device.
        ``type`` is either ``'char'`` or ``'block'``, according to whether the
        device is a character or block device.  ``number`` is the device number
        as integer.

        Return a :class:`Device` object for the device with the given device
        ``number``.  Raise :exc:`DeviceNotFoundByNumberError`, if no device was
        found with the given device type and number.

        .. versionadded:: 0.18
        r)r$Zudev_device_new_from_devnumrrr%)rr �typ�numberr&r!r!r"�from_device_number�s
%
zDevices.from_device_numbercCsVyt|�}tj|�j}Wn.ttfk
rF}zt|��WYdd}~XnX|j|||�S)a�
        Create a new device from the given device file:

        >>> from pyudev import Context, Device
        >>> context = Context()
        >>> device = Devices.from_device_file(context, '/dev/sda')
        >>> device
        Device(u'/sys/devices/pci0000:00/0000:00:0d.0/host2/target2:0:0/2:0:0:0/block/sda')
        >>> device.device_node
        u'/dev/sda'

        .. warning::

           Though the example seems to suggest that ``device.device_node ==
           filename`` holds with ``device = Devices.from_device_file(context,
           filename)``, this is only true in a majority of cases.  There *can*
           be devices, for which this relation is actually false!  Thus, do
           *not* expect :attr:`~Device.device_node` to be equal to the given
           ``filename`` for the returned :class:`Device`.  Especially, use
           :attr:`~Device.device_node` if you need the device file of a
           :class:`Device` created with this method afterwards.

        ``context`` is the :class:`Context` in which to search the device.
        ``filename`` is a string containing the path of a device file.

        Return a :class:`Device` representing the given device file.  Raise
        :exc:`DeviceNotFoundByFileError` if ``filename`` is no device file
        at all or if ``filename`` does not exist or if its metadata was
        inaccessible.

        .. versionadded:: 0.18
        N)rr�stat�st_rdev�EnvironmentError�
ValueErrorrr/)rr �filename�device_type�
device_number�errr!r!r"�from_device_file�s"zDevices.from_device_filecs<|jdd�}t�fdd�|D�d�}|dk	r0|St���dS)a?
        Locate a device based on the interface index.

        :param `Context` context: the libudev context
        :param int ifindex: the interface index
        :returns: the device corresponding to the interface index
        :rtype: `Device`

        This method is only appropriate for network devices.
        Znet)r*c3s"|]}|jjd��kr|VqdS)�ifindexN)�
attributes�get)�.0�d)r9r!r"�	<genexpr>�sz/Devices.from_interface_index.<locals>.<genexpr>N)�list_devices�nextr)rr r9Znetwork_devicesZdevr!)r9r"�from_interface_index�szDevices.from_interface_indexcCs�|d}|dd�}|dkrltjd�}|j|�}|rbtjt|jd��t|jd���}|j|||�St|��nT|d	kr�|j	||�S|d
kr�|j
d�\}}	}
|
r�|r�|j|||
�St|��nt|��dS)
a
        Locate a device based on the kernel device.

        :param `Context` context: the libudev context
        :param str kernel_device: the kernel device
        :returns: the device corresponding to ``kernel_device``
        :rtype: `Device`
        r�N�b�cz^(?P<major>\d+):(?P<minor>\d+)$�major�minor�n�+�:)rCrD)�re�compile�matchr�makedev�int�groupr/r
rA�	partitionr,)rr Z
kernel_deviceZswitch_char�restZ	number_rerLr.r*�_Zkernel_device_namer!r!r"�from_kernel_device�s&




zDevices.from_kernel_devicecCs |jj|�}|st��t||�S)a�
        Create a new device from the process environment (as in
        :data:`os.environ`).

        This only works reliable, if the current process is called from an
        udev rule, and is usually used for tools executed from ``IMPORT=``
        rules.  Use this method to create device objects in Python scripts
        called from udev rules.

        ``context`` is the library :class:`Context`.

        Return a :class:`Device` object constructed from the environment.
        Raise :exc:`DeviceNotFoundInEnvironmentError`, if no device could be
        created from the environment.

        .. udevversion:: 152

        .. versionadded:: 0.18
        )r$Z udev_device_new_from_environmentrr%)rr r&r!r!r"�from_environmentszDevices.from_environmentcCs|j|j|j|j|jgS)z�
        Return methods that obtain a :class:`Device` from a variety of
        different data.

        :return: a list of from_* methods.
        :rtype: list of class methods

        .. versionadded:: 0.18
        )r8r/r,r#r)rr!r!r"�METHODS9s
zDevices.METHODSN)�__name__�
__module__�__qualname__�__doc__�classmethodr#rr,r/r8rArSrTrUr!r!r!r"r7s++#rc@s�eZdZdZedd��Zedd��Zedd��Zedd	��Zed
d��Z	edd
��Z
dd�Zdd�Zdd�Z
edd��Zedd��Zedd��ZdYdd�Zdd�Zedd ��Zed!d"��Zed#d$��Zed%d&��Zed'd(��Zed)d*��Zed+d,��Zed-d.��Zed/d0��Zed1d2��Zed3d4��Zed5d6��Zed7d8��Z ed9d:��Z!ed;d<��Z"ed=d>��Z#ed?d@��Z$dAdB�Z%dCdD�Z&dEdF�Z'dGdH�Z(dIdJ�Z)dKdL�Z*dMdN�Z+dOdP�Z,dQdR�Z-dSdT�Z.dUdV�Z/dWdX�Z0dS)Zr%a�
    A single device with attached attributes and properties.

    This class subclasses the ``Mapping`` ABC, providing a read-only
    dictionary mapping property names to the corresponding values.
    Therefore all well-known dicitionary methods and operators
    (e.g. ``.keys()``, ``.items()``, ``in``) are available to access device
    properties.

    Aside of the properties, a device also has a set of udev-specific
    attributes like the path inside ``sysfs``.

    :class:`Device` objects compare equal and unequal to other devices and
    to strings (based on :attr:`device_path`).  However, there is no
    ordering on :class:`Device` objects, and the corresponding operators
    ``>``, ``<``, ``<=`` and ``>=`` raise :exc:`~exceptions.TypeError`.

    .. warning::

       **Never** use object identity (``is`` operator) to compare
       :class:`Device` objects.  :mod:`pyudev` may create multiple
       :class:`Device` objects for the same device.  Instead compare
       devices by value using ``==`` or ``!=``.

    :class:`Device` objects are hashable and can therefore be used as keys
    in dictionaries and sets.

    They can also be given directly as ``udev_device *`` to functions wrapped
    through :mod:`ctypes`.
    cCs$ddl}|jdtdd�tj||�S)zw
        .. versionadded:: 0.4
        .. deprecated:: 0.18
           Use :class:`Devices.from_path` instead.
        rNz>Will be removed in 1.0. Use equivalent Devices method instead.�)�
stacklevel)�warnings�warn�DeprecationWarningrr#)rr rr]r!r!r"r#nszDevice.from_pathcCs$ddl}|jdtdd�tj||�S)a|
        .. versionchanged:: 0.4
           Raise :exc:`NoSuchDeviceError` instead of returning ``None``, if
           no device was found for ``sys_path``.
        .. versionchanged:: 0.5
           Raise :exc:`DeviceNotFoundAtPathError` instead of
           :exc:`NoSuchDeviceError`.
        .. deprecated:: 0.18
           Use :class:`Devices.from_sys_path` instead.
        rNz>Will be removed in 1.0. Use equivalent Devices method instead.r[)r\)r]r^r_rr)rr rr]r!r!r"r}szDevice.from_sys_pathcCs&ddl}|jdtdd�tj|||�S)zw
        .. versionadded:: 0.5
        .. deprecated:: 0.18
           Use :class:`Devices.from_name` instead.
        rNz>Will be removed in 1.0. Use equivalent Devices method instead.r[)r\)r]r^r_rr,)rr r*r+r]r!r!r"r,�szDevice.from_namecCs&ddl}|jdtdd�tj|||�S)z�
        .. versionadded:: 0.11
        .. deprecated:: 0.18
           Use :class:`Devices.from_device_number` instead.
        rNz>Will be removed in 1.0. Use equivalent Devices method instead.r[)r\)r]r^r_rr/)rr r-r.r]r!r!r"r/�szDevice.from_device_numbercCs$ddl}|jdtdd�tj||�S)z
        .. versionadded:: 0.15
        .. deprecated:: 0.18
           Use :class:`Devices.from_device_file` instead.
        rNz>Will be removed in 1.0. Use equivalent Devices method instead.r[)r\)r]r^r_rr8)rr r4r]r!r!r"r8�szDevice.from_device_filecCs"ddl}|jdtdd�tj|�S)z~
        .. versionadded:: 0.6
        .. deprecated:: 0.18
           Use :class:`Devices.from_environment` instead.
        rNz>Will be removed in 1.0. Use equivalent Devices method instead.r[)r\)r]r^r_rrT)rr r]r!r!r"rT�szDevice.from_environmentcCs||_||_|j|_dS)N)r Z_as_parameter_r$)�selfr Z_devicer!r!r"�__init__�szDevice.__init__cCs|jj|�dS)N)r$Zudev_device_unref)r`r!r!r"�__del__�szDevice.__del__cCs
dj|�S)NzDevice({0.sys_path!r}))�format)r`r!r!r"�__repr__�szDevice.__repr__cCs(|jj|�}|sdSt|j|jj|��S)z_
        The parent :class:`Device` or ``None``, if there is no parent
        device.
        N)r$Zudev_device_get_parentr%r �udev_device_ref)r`�parentr!r!r"rf�sz
Device.parentccs,x&|jj�j|�D]}||kr|VqWdS)a�
        Yield all direct children of this device.

        .. note::

           In udev, parent-child relationships are generally ambiguous, i.e.
           a parent can have multiple children, *and* a child can have multiple
           parents. Hence, `child.parent == parent` does generally *not* hold
           for all `child` objects in `parent.children`. In other words,
           the :attr:`parent` of a device in this property can be different
           from this device!

        .. note::

           As the underlying library does not provide any means to directly
           query the children of a device, this property performs a linear
           search through all devices.

        Return an iterable yielding a :class:`Device` object for each direct
        child of this device.

        .. udevversion:: 172

        .. versionchanged:: 0.13
           Requires udev version 172 now.
        N)r r?Zmatch_parent)r`r&r!r!r"�children�szDevice.childrenccs$|j}x|dk	r|V|j}qWdS)z�
        Yield all ancestors of this device from bottom to top.

        Return an iterator yielding a :class:`Device` object for each
        ancestor of this device from bottom to top.

        .. versionadded:: 0.16
        N)rf)r`rfr!r!r"�	ancestorss

zDevice.ancestorsNcCsDt|�}|dk	rt|�}|jj|||�}|s0dSt|j|jj|��S)a�
        Find the parent device with the given ``subsystem`` and
        ``device_type``.

        ``subsystem`` is a byte or unicode string containing the name of the
        subsystem, in which to search for the parent.  ``device_type`` is a
        byte or unicode string holding the expected device type of the parent.
        It can be ``None`` (the default), which means, that no specific device
        type is expected.

        Return a parent :class:`Device` within the given ``subsystem`` and, if
        ``device_type`` is not ``None``, with the given ``device_type``, or
        ``None``, if this device has no parent device matching these
        constraints.

        .. versionadded:: 0.9
        N)rr$Z-udev_device_get_parent_with_subsystem_devtyper%r re)r`r*r5rfr!r!r"�find_parents
zDevice.find_parentcCsddl}|jdtdd�|jS)a~
        Traverse all parent devices of this device from bottom to top.

        Return an iterable yielding all parent devices as :class:`Device`
        objects, *not* including the current device.  The last yielded
        :class:`Device` is the top of the device hierarchy.

        .. deprecated:: 0.16
           Will be removed in 1.0. Use :attr:`ancestors` instead.
        rNz5Will be removed in 1.0. Use Device.ancestors instead.r[)r\)r]r^r_rh)r`r]r!r!r"�traverse0szDevice.traversecCst|jj|��S)zz
        Absolute path of this device in ``sysfs`` including the ``sysfs``
        mount point as unicode string.
        )rr$Zudev_device_get_syspath)r`r!r!r"rCszDevice.sys_pathcCst|jj|��S)a
        Kernel device path as unicode string.  This path uniquely identifies
        a single device.

        Unlike :attr:`sys_path`, this path does not contain the ``sysfs``
        mount point.  However, the path is absolute and starts with a slash
        ``'/'``.
        )rr$Zudev_device_get_devpath)r`r!r!r"�device_pathLs
zDevice.device_pathcCs |jj|�}|dkrdSt|�S)z�
        Name of the subsystem this device is part of as unicode string.

        :returns: name of subsystem if found, else None
        :rtype: unicode string or NoneType
        N)r$Zudev_device_get_subsystemr)r`Zsubsysr!r!r"r*YszDevice.subsystemcCst|jj|��S)zF
        Device file name inside ``sysfs`` as unicode string.
        )rr$Zudev_device_get_sysname)r`r!r!r"r+dszDevice.sys_namecCs |jj|�}|dk	rt|�SdS)a�
        The trailing number of the :attr:`sys_name` as unicode string, or
        ``None``, if the device has no trailing number in its name.

        .. note::

           The number is returned as unicode string to preserve the exact
           format of the number, especially any leading zeros:

           >>> from pyudev import Context, Device
           >>> context = Context()
           >>> device = Devices.from_path(context, '/sys/devices/LNXSYSTM:00')
           >>> device.sys_number
           u'00'

           To work with numbers, explicitly convert them to ints:

           >>> int(device.sys_number)
           0

        .. versionadded:: 0.11
        N)r$Zudev_device_get_sysnumr)r`r.r!r!r"�
sys_numberlszDevice.sys_numbercCs$|jj|�}|dk	rt|�S|SdS)a�
        Device type as unicode string, or ``None``, if the device type is
        unknown.

        >>> from pyudev import Context
        >>> context = Context()
        >>> for device in context.list_devices(subsystem='net'):
        ...     '{0} - {1}'.format(device.sys_name, device.device_type or 'ethernet')
        ...
        u'eth0 - ethernet'
        u'wlan0 - wlan'
        u'lo - ethernet'
        u'vboxnet0 - ethernet'

        .. versionadded:: 0.10
        N)r$Zudev_device_get_devtyper)r`r5r!r!r"r5�szDevice.device_typecCs |jj|�}|dk	rt|�SdS)z�
        The driver name as unicode string, or ``None``, if there is no
        driver for this device.

        .. versionadded:: 0.5
        N)r$Zudev_device_get_driverr)r`�driverr!r!r"rm�sz
Device.drivercCs |jj|�}|dk	rt|�SdS)a�
        Absolute path to the device node of this device as unicode string or
        ``None``, if this device doesn't have a device node.  The path
        includes the device directory (see :attr:`Context.device_path`).

        This path always points to the actual device node associated with
        this device, and never to any symbolic links to this device node.
        See :attr:`device_links` to get a list of symbolic links to this
        device node.

        .. warning::

           For devices created with :meth:`from_device_file()`, the value of
           this property is not necessary equal to the ``filename`` given to
           :meth:`from_device_file()`.
        N)r$Zudev_device_get_devnoder)r`Znoder!r!r"�device_node�szDevice.device_nodecCs|jj|�S)a
        The device number of the associated device as integer, or ``0``, if no
        device number is associated.

        Use :func:`os.major` and :func:`os.minor` to decompose the device
        number into its major and minor number:

        >>> import os
        >>> from pyudev import Context, Device
        >>> context = Context()
        >>> sda = Devices.from_name(context, 'block', 'sda')
        >>> sda.device_number
        2048L
        >>> (os.major(sda.device_number), os.minor(sda.device_number))
        (8, 0)

        For devices with an associated :attr:`device_node`, this is the same as
        the ``st_rdev`` field of the stat result of the :attr:`device_node`:

        >>> os.stat(sda.device_node).st_rdev
        2048

        .. versionadded:: 0.11
        )r$Zudev_device_get_devnum)r`r!r!r"r6�szDevice.device_numbercCst|jj|��S)ai
        ``True``, if the device is initialized, ``False`` otherwise.

        A device is initialized, if udev has already handled this device and
        has set up device node permissions and context, or renamed a network
        device.

        Consequently, this property is only implemented for devices with a
        device node or for network devices.  On all other devices this property
        is always ``True``.

        It is *not* recommended, that you use uninitialized devices.

        .. seealso:: :attr:`time_since_initialized`

        .. udevversion:: 165

        .. versionadded:: 0.8
        )�boolr$Zudev_device_get_is_initialized)r`r!r!r"�is_initialized�szDevice.is_initializedcCs|jj|�}t|d�S)a�
        The time elapsed since initialization as :class:`~datetime.timedelta`.

        This property is only implemented on devices, which need to store
        properties in the udev database.  On all other devices this property is
        simply zero :class:`~datetime.timedelta`.

        .. seealso:: :attr:`is_initialized`

        .. udevversion:: 165

        .. versionadded:: 0.8
        )�microseconds)r$Z&udev_device_get_usec_since_initializedr	)r`rqr!r!r"�time_since_initialized�szDevice.time_since_initializedccs4|jj|�}x"t|j|�D]\}}t|�VqWdS)a�
        An iterator, which yields the absolute paths (including the device
        directory, see :attr:`Context.device_path`) of all symbolic links
        pointing to the :attr:`device_node` of this device.  The paths are
        unicode strings.

        UDev can create symlinks to the original device node (see
        :attr:`device_node`) inside the device directory.  This is often
        used to assign a constant, fixed device node to devices like
        removeable media, which technically do not have a constant device
        node, or to map a single device into multiple device hierarchies.
        The property provides access to all such symbolic links, which were
        created by UDev for this device.

        .. warning::

           Links are not necessarily resolved by
           :meth:`Devices.from_device_file()`. Hence do *not* rely on
           ``Devices.from_device_file(context, link).device_path ==
           device.device_path`` from any ``link`` in ``device.device_links``.
        N)r$Z#udev_device_get_devlinks_list_entryrr)r`Zdevlinks�namerRr!r!r"�device_linksszDevice.device_linkscCs |jj|�}|dk	rt|�SdS)a
        The device event action as string, or ``None``, if this device was not
        received from a :class:`Monitor`.

        Usual actions are:

        ``'add'``
          A device has been added (e.g. a USB device was plugged in)
        ``'remove'``
          A device has been removed (e.g. a USB device was unplugged)
        ``'change'``
          Something about the device changed (e.g. a device property)
        ``'online'``
          The device is online now
        ``'offline'``
          The device is offline now

        .. warning::

           Though the actions listed above are the most common, this property
           *may* return other values, too, so be prepared to handle unknown
           actions!

        .. versionadded:: 0.16
        N)r$Zudev_device_get_actionr)r`�actionr!r!r"ru sz
Device.actioncCs|jj|�S)z�
        The device event sequence number as integer, or ``0`` if this device
        has no sequence number, i.e. was not received from a :class:`Monitor`.

        .. versionadded:: 0.16
        )r$Zudev_device_get_seqnum)r`r!r!r"�sequence_number>szDevice.sequence_numbercCst|�S)aT
        The system attributes of this device as read-only
        :class:`Attributes` mapping.

        System attributes are basically normal files inside the the device
        directory.  These files contain all sorts of information about the
        device, which may not be reflected by properties.  These attributes
        are commonly used for matching in udev rules, and can be printed
        using ``udevadm info --attribute-walk``.

        The values of these attributes are not always proper strings, and
        can contain arbitrary bytes.

        .. versionadded:: 0.5
        )�
Attributes)r`r!r!r"r:HszDevice.attributescCst|�S)zu
        The udev properties of this object as read-only Properties mapping.

        .. versionadded:: 0.21
        )�
Properties)r`r!r!r"�
properties_szDevice.propertiescCst|�S)a�
        A :class:`Tags` object representing the tags attached to this device.

        The :class:`Tags` object supports a test for a single tag as well as
        iteration over all tags:

        >>> from pyudev import Context
        >>> context = Context()
        >>> device = next(iter(context.list_devices(tag='systemd')))
        >>> 'systemd' in device.tags
        True
        >>> list(device.tags)
        [u'seat', u'systemd', u'uaccess']

        Tags are arbitrary classifiers that can be attached to devices by udev
        scripts and daemons.  For instance, systemd_ uses tags for multi-seat_
        support.

        .. _systemd: http://freedesktop.org/wiki/Software/systemd
        .. _multi-seat: http://www.freedesktop.org/wiki/Software/systemd/multiseat

        .. udevversion:: 154

        .. versionadded:: 0.6

        .. versionchanged:: 0.13
           Return a :class:`Tags` object now.
        )�Tags)r`r!r!r"�tagshszDevice.tagscCs"ddl}|jdtdd�|jj�S)a*
        Iterate over the names of all properties defined for this device.

        Return a generator yielding the names of all properties of this
        device as unicode strings.

        .. deprecated:: 0.21
           Will be removed in 1.0. Access properties with Device.properties.
        rNzAWill be removed in 1.0. Access properties with Device.properties.r[)r\)r]r^r_ry�__iter__)r`r]r!r!r"r|�s
zDevice.__iter__cCs"ddl}|jdtdd�|jj�S)z�
        Return the amount of properties defined for this device as integer.

        .. deprecated:: 0.21
           Will be removed in 1.0. Access properties with Device.properties.
        rNzAWill be removed in 1.0. Access properties with Device.properties.r[)r\)r]r^r_ry�__len__)r`r]r!r!r"r}�szDevice.__len__cCs$ddl}|jdtdd�|jj|�S)a�
        Get the given property from this device.

        ``prop`` is a unicode or byte string containing the name of the
        property.

        Return the property value as unicode string, or raise a
        :exc:`~exceptions.KeyError`, if the given property is not defined
        for this device.

        .. deprecated:: 0.21
           Will be removed in 1.0. Access properties with Device.properties.
        rNzAWill be removed in 1.0. Access properties with Device.properties.r[)r\)r]r^r_ry�__getitem__)r`�propr]r!r!r"r~�szDevice.__getitem__cCs$ddl}|jdtdd�|jj|�S)a
        Get the given property from this device as integer.

        ``prop`` is a unicode or byte string containing the name of the
        property.

        Return the property value as integer. Raise a
        :exc:`~exceptions.KeyError`, if the given property is not defined
        for this device, or a :exc:`~exceptions.ValueError`, if the property
        value cannot be converted to an integer.

        .. deprecated:: 0.21
           Will be removed in 1.0. Use Device.properties.asint() instead.
        rNz<Will be removed in 1.0. Use Device.properties.asint instead.r[)r\)r]r^r_ry�asint)r`rr]r!r!r"r��szDevice.asintcCs$ddl}|jdtdd�|jj|�S)a�
        Get the given property from this device as boolean.

        A boolean property has either a value of ``'1'`` or of ``'0'``,
        where ``'1'`` stands for ``True``, and ``'0'`` for ``False``.  Any
        other value causes a :exc:`~exceptions.ValueError` to be raised.

        ``prop`` is a unicode or byte string containing the name of the
        property.

        Return ``True``, if the property value is ``'1'`` and ``False``, if
        the property value is ``'0'``.  Any other value raises a
        :exc:`~exceptions.ValueError`.  Raise a :exc:`~exceptions.KeyError`,
        if the given property is not defined for this device.

        .. deprecated:: 0.21
           Will be removed in 1.0. Use Device.properties.asbool() instead.
        rNz=Will be removed in 1.0. Use Device.properties.asbool instead.r[)r\)r]r^r_ry�asbool)r`rr]r!r!r"r��sz
Device.asboolcCs
t|j�S)N)�hashrk)r`r!r!r"�__hash__�szDevice.__hash__cCs$t|t�r|j|jkS|j|kSdS)N)�
isinstancer%rk)r`�otherr!r!r"�__eq__�s
z
Device.__eq__cCs$t|t�r|j|jkS|j|kSdS)N)r�r%rk)r`r�r!r!r"�__ne__�s
z
Device.__ne__cCstd��dS)NzDevice not orderable)�	TypeError)r`r�r!r!r"�__gt__sz
Device.__gt__cCstd��dS)NzDevice not orderable)r�)r`r�r!r!r"�__lt__sz
Device.__lt__cCstd��dS)NzDevice not orderable)r�)r`r�r!r!r"�__le__sz
Device.__le__cCstd��dS)NzDevice not orderable)r�)r`r�r!r!r"�__ge__	sz
Device.__ge__)N)1rVrWrXrYrZr#rr,r/r8rTrarbrd�propertyrfrgrhrirjrrkr*r+rlr5rmrnr6rprrrtrurvr:ryr{r|r}r~r�r�r�r�r�r�r�r�r�r!r!r!r"r%MsX
 
	

	 r%c@s@eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dS)rxzN
    udev properties :class:`Device` objects.

    .. versionadded:: 0.21
    cCs||_|j|_dS)N)r&r$)r`r&r!r!r"raszProperties.__init__ccs6|jj|j�}x"t|j|�D]\}}t|�VqWdS)z�
        Iterate over the names of all properties defined for the device.

        Return a generator yielding the names of all properties of this
        device as unicode strings.
        N)r$�%udev_device_get_properties_list_entryr&rr)r`ryrsrRr!r!r"r|szProperties.__iter__cCs(|jj|j�}tdd�t|j|�D��S)zU
        Return the amount of properties defined for this device as integer.
        css|]
}dVqdS)rBNr!)r<rRr!r!r"r>*sz%Properties.__len__.<locals>.<genexpr>)r$r�r&�sumr)r`ryr!r!r"r}$szProperties.__len__cCs,|jj|jt|��}|dkr$t|��t|�S)a9
        Get the given property from this device.

        ``prop`` is a unicode or byte string containing the name of the
        property.

        Return the property value as unicode string, or raise a
        :exc:`~exceptions.KeyError`, if the given property is not defined
        for this device.
        N)r$Zudev_device_get_property_valuer&r�KeyErrorr)r`r�valuer!r!r"r~,s
zProperties.__getitem__cCst||�S)a�
        Get the given property from this device as integer.

        ``prop`` is a unicode or byte string containing the name of the
        property.

        Return the property value as integer. Raise a
        :exc:`~exceptions.KeyError`, if the given property is not defined
        for this device, or a :exc:`~exceptions.ValueError`, if the property
        value cannot be converted to an integer.
        )rN)r`rr!r!r"r�?szProperties.asintcCst||�S)a�
        Get the given property from this device as boolean.

        A boolean property has either a value of ``'1'`` or of ``'0'``,
        where ``'1'`` stands for ``True``, and ``'0'`` for ``False``.  Any
        other value causes a :exc:`~exceptions.ValueError` to be raised.

        ``prop`` is a unicode or byte string containing the name of the
        property.

        Return ``True``, if the property value is ``'1'`` and ``False``, if
        the property value is ``'0'``.  Any other value raises a
        :exc:`~exceptions.ValueError`.  Raise a :exc:`~exceptions.KeyError`,
        if the given property is not defined for this device.
        )r)r`rr!r!r"r�MszProperties.asboolN)
rVrWrXrYrar|r}r~r�r�r!r!r!r"rx
srxc@sNeZdZdZdd�Zedd��Zdd�Zdd	d
�Zdd�Z	d
d�Z
dd�ZdS)rwzQ
    udev attributes for :class:`Device` objects.

    .. versionadded:: 0.5
    cCs||_|j|_dS)N)r&r$)r`r&r!r!r"ragszAttributes.__init__ccsFt|jd�sdS|jj|j�}x"t|j|�D]\}}t|�Vq,WdS)a�
        Yield the ``available`` attributes for the device.

        It is not guaranteed that a key in this list will have a value.
        It is not guaranteed that a key not in this list will not have a value.

        It is guaranteed that the keys in this list are the keys that libudev
        considers to be "available" attributes.

        If libudev version does not define udev_device_get_sysattr_list_entry()
        yields nothing.

        See rhbz#1267584.
        �"udev_device_get_sysattr_list_entryN)�hasattrr$r�r&rr)r`�attrs�	attributerRr!r!r"�available_attributesks
zAttributes.available_attributescCs(|jj|jt|��}|dkr$t|��|S)aD
        Get the given system ``attribute`` for the device.

        :param attribute: the key for an attribute value
        :type attribute: unicode or byte string
        :returns: the value corresponding to ``attribute``
        :rtype: an arbitrary sequence of bytes
        :raises KeyError: if no value found
        N)r$Zudev_device_get_sysattr_valuer&rr�)r`r�r�r!r!r"�_get�s

zAttributes._getNcCs$y
|j|�Stk
r|SXdS)a|
        Get the given system ``attribute`` for the device.

        :param attribute: the key for an attribute value
        :type attribute: unicode or byte string
        :param default: a default if no corresponding value found
        :type default: a sequence of bytes
        :returns: the value corresponding to ``attribute`` or ``default``
        :rtype: object
        N)r�r�)r`r��defaultr!r!r"r;�s
zAttributes.getcCst|j|��S)a�
        Get the given ``attribute`` for the device as unicode string.

        :param attribute: the key for an attribute value
        :type attribute: unicode or byte string
        :returns: the value corresponding to ``attribute``, as unicode
        :rtype: unicode
        :raises KeyError: if no value found for ``attribute``
        :raises UnicodeDecodeError: if value is not convertible
        )rr�)r`r�r!r!r"�asstring�szAttributes.asstringcCst|j|��S)a�
        Get the given ``attribute`` as an int.

        :param attribute: the key for an attribute value
        :type attribute: unicode or byte string
        :returns: the value corresponding to ``attribute``, as an int
        :rtype: int
        :raises KeyError: if no value found for ``attribute``
        :raises UnicodeDecodeError: if value is not convertible to unicode
        :raises ValueError: if unicode value can not be converted to an int
        )rNr�)r`r�r!r!r"r��szAttributes.asintcCst|j|��S)a�
        Get the given ``attribute`` from this device as a bool.

        :param attribute: the key for an attribute value
        :type attribute: unicode or byte string
        :returns: the value corresponding to ``attribute``, as bool
        :rtype: bool
        :raises KeyError: if no value found for ``attribute``
        :raises UnicodeDecodeError: if value is not convertible to unicode
        :raises ValueError: if unicode value can not be converted to a bool

        A boolean attribute has either a value of ``'1'`` or of ``'0'``,
        where ``'1'`` stands for ``True``, and ``'0'`` for ``False``.  Any
        other value causes a :exc:`~exceptions.ValueError` to be raised.
        )rr�)r`r�r!r!r"r��szAttributes.asbool)N)rVrWrXrYrar�r�r�r;r�r�r�r!r!r!r"rw`s

rwc@s0eZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)rzzk
    A iterable over :class:`Device` tags.

    Subclasses the ``Container`` and the ``Iterable`` ABC.
    cCs||_|j|_dS)N)r&r$)r`r&r!r!r"ra�sz
Tags.__init__cs>t|jd�r$t|jj|jt����St�fdd�|D��SdS)z
            Whether ``tag`` exists.

            :param tag: unicode string with name of tag
            :rtype: bool
        �udev_device_has_tagc3s|]}|�kVqdS)Nr!)r<�t)�tagr!r"r>�sz Tags._has_tag.<locals>.<genexpr>N)r�r$ror�r&r�any)r`r�r!)r�r"�_has_tag�sz
Tags._has_tagcCs
|j|�S)z�
        Check for existence of ``tag``.

        ``tag`` is a tag as unicode string.

        Return ``True``, if ``tag`` is attached to the device, ``False``
        otherwise.
        )r�)r`r�r!r!r"�__contains__�s	zTags.__contains__ccs6|jj|j�}x"t|j|�D]\}}t|�VqWdS)zS
        Iterate over all tags.

        Yield each tag as unicode string.
        N)r$Zudev_device_get_tags_list_entryr&rr)r`r{r�rRr!r!r"r|�sz
Tags.__iter__N)rVrWrXrYrar�r�r|r!r!r!r"rz�s

rz)"rYZ
__future__rrrrrrJ�collectionsrrrZdatetimer	Zpyudev.device._errorsr
rrr
rrrZpyudev._utilrrrrr�objectrr%rxrwrzr!r!r!r"�<module>sDESqdevice/__pycache__/_errors.cpython-36.opt-1.pyc000064400000014370150351420050015253 0ustar003

5�Vl�@sdZddlmZddlmZddlmZddlmZddlZddlmZeej	�Gdd	�d	e
��Zeej	�Gd
d�de��ZGdd
�d
e�Z
Gdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZdS)z�
    pyudev.device._errors
    =====================

    Errors raised by Device methods.

    .. moduleauthor:: Sebastian Wiesner <lunaryorn@gmail.com>
�)�absolute_import)�division)�print_function)�unicode_literalsN)�
add_metaclassc@seZdZdZdS)�DeviceErrorzP
    Any error raised when messing around w/ or trying to discover devices.
    N)�__name__�
__module__�__qualname__�__doc__�rr�/usr/lib/python3.6/_errors.pyr$src@seZdZdZdS)�DeviceNotFoundErrorz�
    An exception indicating that no :class:`Device` was found.

    .. versionchanged:: 0.5
       Rename from ``NoSuchDeviceError`` to its current name.
    N)rr	r
rrrrr
r+src@s,eZdZdZdd�Zedd��Zdd�ZdS)	�DeviceNotFoundAtPathErrorzh
    A :exc:`DeviceNotFoundError` indicating that no :class:`Device` was
    found at a given path.
    cCstj||�dS)N)r�__init__)�self�sys_pathrrr
r;sz"DeviceNotFoundAtPathError.__init__cCs
|jdS)z<
        The path that caused this error as string.
        r)�args)rrrr
r>sz"DeviceNotFoundAtPathError.sys_pathcCsdj|j�S)NzNo device at {0!r})�formatr)rrrr
�__str__Esz!DeviceNotFoundAtPathError.__str__N)rr	r
rr�propertyrrrrrr
r5src@seZdZdZdS)�DeviceNotFoundByFileErrorzp
    A :exc:`DeviceNotFoundError` indicating that no :class:`Device` was
    found from the given filename.
    N)rr	r
rrrrr
rIsrc@seZdZdZdS)�#DeviceNotFoundByInterfaceIndexErrorzw
    A :exc:`DeviceNotFoundError` indicating that no :class:`Device` was found
    from the given interface index.
    N)rr	r
rrrrr
rOsrc@seZdZdZdS)�!DeviceNotFoundByKernelDeviceErrorz�
    A :exc:`DeviceNotFoundError` indicating that no :class:`Device` was found
    from the given kernel device string.

    The format of the kernel device string is defined in the
    systemd.journal-fields man pagees.
    N)rr	r
rrrrr
rUsrc@s8eZdZdZdd�Zedd��Zedd��Zdd	�Zd
S)�DeviceNotFoundByNameErrorzj
    A :exc:`DeviceNotFoundError` indicating that no :class:`Device` was
    found with a given name.
    cCstj|||�dS)N)rr)r�	subsystem�sys_namerrr
resz"DeviceNotFoundByNameError.__init__cCs
|jdS)zA
        The subsystem that caused this error as string.
        r)r)rrrr
rhsz#DeviceNotFoundByNameError.subsystemcCs
|jdS)z@
        The sys name that caused this error as string.
        �)r)rrrr
rosz"DeviceNotFoundByNameError.sys_namecCs
dj|�S)Nz+No device {0.sys_name!r} in {0.subsystem!r})r)rrrr
rvsz!DeviceNotFoundByNameError.__str__N)	rr	r
rrrrrrrrrr
r_s
rc@s8eZdZdZdd�Zedd��Zedd��Zdd	�Zd
S)�DeviceNotFoundByNumberErrorzs
    A :exc:`DeviceNotFoundError` indicating, that no :class:`Device` was found
    for a given device number.
    cCstj|||�dS)N)rr)r�typZnumberrrr
r�sz$DeviceNotFoundByNumberError.__init__cCs
|jdS)zj
        The device type causing this error as string.  Either ``'char'`` or
        ``'block'``.
        r)r)rrrr
�device_type�sz'DeviceNotFoundByNumberError.device_typecCs
|jdS)zB
        The device number causing this error as integer.
        r)r)rrrr
�
device_number�sz)DeviceNotFoundByNumberError.device_numbercCs
dj|�S)Nz7No {0.device_type} device with number {0.device_number})r)rrrr
r�sz#DeviceNotFoundByNumberError.__str__N)	rr	r
rrrr r!rrrrr
rzs
rc@seZdZdZdd�ZdS)� DeviceNotFoundInEnvironmentErrorz�
    A :exc:`DeviceNotFoundError` indicating, that no :class:`Device` could
    be constructed from the process environment.
    cCsdS)NzNo device found in environmentr)rrrr
r�sz(DeviceNotFoundInEnvironmentError.__str__N)rr	r
rrrrrr
r"�sr"c@s&eZdZdZdZddd�Zdd�ZdS)	�DeviceValueErrorz�
    Raised when a parameter has an unacceptable value.

    May also be raised when the parameter has an unacceptable type.
    z+value '%s' for parameter %s is unacceptableNcCs||_||_||_dS)z� Initializer.

            :param object value: the value
            :param str param: the parameter
            :param str msg: an explanatory message
        N)�_value�_param�_msg)r�valueZparam�msgrrr
r�szDeviceValueError.__init__cCs:|jr$|jd}||j|j|jfS|j|j|jfSdS)Nz: %s)r&�_FMT_STRr$r%)rZfmt_strrrr
r�s
zDeviceValueError.__str__)N)rr	r
rr)rrrrrr
r#�s
r#)rZ
__future__rrrr�abcZsixr�ABCMeta�	Exceptionrrrrrrrrr"r#rrrr
�<module>s$	

device/__pycache__/_device.cpython-36.pyc000064400000124641150351420050014242 0ustar003

u1�Wɭ�@sZdZddlmZddlmZddlmZddlmZddlZddlZddlm	Z	ddlm
Z
dd	lmZdd
lm
Z
ddlmZddlmZdd
lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�Z Gdd �d e
e	�Z!dS)!z�
    pyudev.device._device
    =====================

    Device class implementation of :mod:`pyudev`.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
�)�absolute_import)�division)�print_function)�unicode_literalsN)�	Container)�Iterable)�Mapping)�	timedelta)�DeviceNotFoundAtPathError)�DeviceNotFoundByFileError)�#DeviceNotFoundByInterfaceIndexError)�!DeviceNotFoundByKernelDeviceError)�DeviceNotFoundByNameError)�DeviceNotFoundByNumberError)� DeviceNotFoundInEnvironmentError)�ensure_byte_string)�ensure_unicode_string)�get_device_type)�string_to_bool)�udev_list_iteratec@s|eZdZdZedd��Zedd��Zedd��Zedd	��Zed
d��Z	edd
��Z
edd��Zedd��Zedd��Z
dS)�DeviceszT
    Class for constructing :class:`Device` objects from various kinds of data.
    cCs0|j|j�s$tjj|j|jtj��}|j||�S)a�
        Create a device from a device ``path``.  The ``path`` may or may not
        start with the ``sysfs`` mount point:

        >>> from pyudev import Context, Device
        >>> context = Context()
        >>> Devices.from_path(context, '/devices/platform')
        Device(u'/sys/devices/platform')
        >>> Devices.from_path(context, '/sys/devices/platform')
        Device(u'/sys/devices/platform')

        ``context`` is the :class:`Context` in which to search the device.
        ``path`` is a device path as unicode or byte string.

        Return a :class:`Device` object for the device.  Raise
        :exc:`DeviceNotFoundAtPathError`, if no device was found for ``path``.

        .. versionadded:: 0.18
        )�
startswith�sys_path�os�path�join�lstrip�sep�
from_sys_path)�cls�contextr�r!�/usr/lib/python3.6/_device.py�	from_path<szDevices.from_pathcCs(|jj|t|��}|st|��t||�S)a�
        Create a new device from a given ``sys_path``:

        >>> from pyudev import Context, Device
        >>> context = Context()
        >>> Devices.from_sys_path(context, '/sys/devices/platform')
        Device(u'/sys/devices/platform')

        ``context`` is the :class:`Context` in which to search the device.
        ``sys_path`` is a unicode or byte string containing the path of the
        device inside ``sysfs`` with the mount point included.

        Return a :class:`Device` object for the device.  Raise
        :exc:`DeviceNotFoundAtPathError`, if no device was found for
        ``sys_path``.

        .. versionadded:: 0.18
        )�_libudevZudev_device_new_from_syspathrr
�Device)rr r�devicer!r!r"rUs
zDevices.from_sys_pathcCs<|jdd�}|jj|t|�t|��}|s2t||��t||�S)a.
        Create a new device from a given ``subsystem`` and a given
        ``sys_name``:

        >>> from pyudev import Context, Device
        >>> context = Context()
        >>> sda = Devices.from_name(context, 'block', 'sda')
        >>> sda
        Device(u'/sys/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda')
        >>> sda == Devices.from_path(context, '/block/sda')

        ``context`` is the :class:`Context` in which to search the device.
        ``subsystem`` and ``sys_name`` are byte or unicode strings, which
        denote the subsystem and the name of the device to create.

        Return a :class:`Device` object for the device.  Raise
        :exc:`DeviceNotFoundByNameError`, if no device was found with the given
        name.

        .. versionadded:: 0.18
        �/�!)�replacer$Z&udev_device_new_from_subsystem_sysnamerrr%)rr �	subsystem�sys_namer&r!r!r"�	from_nameos

zDevices.from_namecCs0|jj|t|d�|�}|s&t||��t||�S)a�
        Create a new device from a device ``number`` with the given device
        ``type``:

        >>> import os
        >>> from pyudev import Context, Device
        >>> ctx = Context()
        >>> major, minor = 8, 0
        >>> device = Devices.from_device_number(context, 'block',
        ...     os.makedev(major, minor))
        >>> device
        Device(u'/sys/devices/pci0000:00/0000:00:11.0/host0/target0:0:0/0:0:0:0/block/sda')
        >>> os.major(device.device_number), os.minor(device.device_number)
        (8, 0)

        Use :func:`os.makedev` to construct a device number from a major and a
        minor device number, as shown in the example above.

        .. warning::

           Device numbers are not unique across different device types.
           Passing a correct number with a wrong type may silently yield a
           wrong device object, so make sure to pass the correct device type.

        ``context`` is the :class:`Context`, in which to search the device.
        ``type`` is either ``'char'`` or ``'block'``, according to whether the
        device is a character or block device.  ``number`` is the device number
        as integer.

        Return a :class:`Device` object for the device with the given device
        ``number``.  Raise :exc:`DeviceNotFoundByNumberError`, if no device was
        found with the given device type and number.

        .. versionadded:: 0.18
        r)r$Zudev_device_new_from_devnumrrr%)rr �typ�numberr&r!r!r"�from_device_number�s
%
zDevices.from_device_numbercCsVyt|�}tj|�j}Wn.ttfk
rF}zt|��WYdd}~XnX|j|||�S)a�
        Create a new device from the given device file:

        >>> from pyudev import Context, Device
        >>> context = Context()
        >>> device = Devices.from_device_file(context, '/dev/sda')
        >>> device
        Device(u'/sys/devices/pci0000:00/0000:00:0d.0/host2/target2:0:0/2:0:0:0/block/sda')
        >>> device.device_node
        u'/dev/sda'

        .. warning::

           Though the example seems to suggest that ``device.device_node ==
           filename`` holds with ``device = Devices.from_device_file(context,
           filename)``, this is only true in a majority of cases.  There *can*
           be devices, for which this relation is actually false!  Thus, do
           *not* expect :attr:`~Device.device_node` to be equal to the given
           ``filename`` for the returned :class:`Device`.  Especially, use
           :attr:`~Device.device_node` if you need the device file of a
           :class:`Device` created with this method afterwards.

        ``context`` is the :class:`Context` in which to search the device.
        ``filename`` is a string containing the path of a device file.

        Return a :class:`Device` representing the given device file.  Raise
        :exc:`DeviceNotFoundByFileError` if ``filename`` is no device file
        at all or if ``filename`` does not exist or if its metadata was
        inaccessible.

        .. versionadded:: 0.18
        N)rr�stat�st_rdev�EnvironmentError�
ValueErrorrr/)rr �filename�device_type�
device_number�errr!r!r"�from_device_file�s"zDevices.from_device_filecs<|jdd�}t�fdd�|D�d�}|dk	r0|St���dS)a?
        Locate a device based on the interface index.

        :param `Context` context: the libudev context
        :param int ifindex: the interface index
        :returns: the device corresponding to the interface index
        :rtype: `Device`

        This method is only appropriate for network devices.
        Znet)r*c3s"|]}|jjd��kr|VqdS)�ifindexN)�
attributes�get)�.0�d)r9r!r"�	<genexpr>�sz/Devices.from_interface_index.<locals>.<genexpr>N)�list_devices�nextr)rr r9Znetwork_devicesZdevr!)r9r"�from_interface_index�szDevices.from_interface_indexcCs�|d}|dd�}|dkrltjd�}|j|�}|rbtjt|jd��t|jd���}|j|||�St|��nT|d	kr�|j	||�S|d
kr�|j
d�\}}	}
|
r�|r�|j|||
�St|��nt|��dS)
a
        Locate a device based on the kernel device.

        :param `Context` context: the libudev context
        :param str kernel_device: the kernel device
        :returns: the device corresponding to ``kernel_device``
        :rtype: `Device`
        r�N�b�cz^(?P<major>\d+):(?P<minor>\d+)$�major�minor�n�+�:)rCrD)�re�compile�matchr�makedev�int�groupr/r
rA�	partitionr,)rr Z
kernel_deviceZswitch_char�restZ	number_rerLr.r*�_Zkernel_device_namer!r!r"�from_kernel_device�s&




zDevices.from_kernel_devicecCs |jj|�}|st��t||�S)a�
        Create a new device from the process environment (as in
        :data:`os.environ`).

        This only works reliable, if the current process is called from an
        udev rule, and is usually used for tools executed from ``IMPORT=``
        rules.  Use this method to create device objects in Python scripts
        called from udev rules.

        ``context`` is the library :class:`Context`.

        Return a :class:`Device` object constructed from the environment.
        Raise :exc:`DeviceNotFoundInEnvironmentError`, if no device could be
        created from the environment.

        .. udevversion:: 152

        .. versionadded:: 0.18
        )r$Z udev_device_new_from_environmentrr%)rr r&r!r!r"�from_environmentszDevices.from_environmentcCs|j|j|j|j|jgS)z�
        Return methods that obtain a :class:`Device` from a variety of
        different data.

        :return: a list of from_* methods.
        :rtype: list of class methods

        .. versionadded:: 0.18
        )r8r/r,r#r)rr!r!r"�METHODS9s
zDevices.METHODSN)�__name__�
__module__�__qualname__�__doc__�classmethodr#rr,r/r8rArSrTrUr!r!r!r"r7s++#rc@s�eZdZdZedd��Zedd��Zedd��Zedd	��Zed
d��Z	edd
��Z
dd�Zdd�Zdd�Z
edd��Zedd��Zedd��ZdYdd�Zdd�Zedd ��Zed!d"��Zed#d$��Zed%d&��Zed'd(��Zed)d*��Zed+d,��Zed-d.��Zed/d0��Zed1d2��Zed3d4��Zed5d6��Zed7d8��Z ed9d:��Z!ed;d<��Z"ed=d>��Z#ed?d@��Z$dAdB�Z%dCdD�Z&dEdF�Z'dGdH�Z(dIdJ�Z)dKdL�Z*dMdN�Z+dOdP�Z,dQdR�Z-dSdT�Z.dUdV�Z/dWdX�Z0dS)Zr%a�
    A single device with attached attributes and properties.

    This class subclasses the ``Mapping`` ABC, providing a read-only
    dictionary mapping property names to the corresponding values.
    Therefore all well-known dicitionary methods and operators
    (e.g. ``.keys()``, ``.items()``, ``in``) are available to access device
    properties.

    Aside of the properties, a device also has a set of udev-specific
    attributes like the path inside ``sysfs``.

    :class:`Device` objects compare equal and unequal to other devices and
    to strings (based on :attr:`device_path`).  However, there is no
    ordering on :class:`Device` objects, and the corresponding operators
    ``>``, ``<``, ``<=`` and ``>=`` raise :exc:`~exceptions.TypeError`.

    .. warning::

       **Never** use object identity (``is`` operator) to compare
       :class:`Device` objects.  :mod:`pyudev` may create multiple
       :class:`Device` objects for the same device.  Instead compare
       devices by value using ``==`` or ``!=``.

    :class:`Device` objects are hashable and can therefore be used as keys
    in dictionaries and sets.

    They can also be given directly as ``udev_device *`` to functions wrapped
    through :mod:`ctypes`.
    cCs$ddl}|jdtdd�tj||�S)zw
        .. versionadded:: 0.4
        .. deprecated:: 0.18
           Use :class:`Devices.from_path` instead.
        rNz>Will be removed in 1.0. Use equivalent Devices method instead.�)�
stacklevel)�warnings�warn�DeprecationWarningrr#)rr rr]r!r!r"r#nszDevice.from_pathcCs$ddl}|jdtdd�tj||�S)a|
        .. versionchanged:: 0.4
           Raise :exc:`NoSuchDeviceError` instead of returning ``None``, if
           no device was found for ``sys_path``.
        .. versionchanged:: 0.5
           Raise :exc:`DeviceNotFoundAtPathError` instead of
           :exc:`NoSuchDeviceError`.
        .. deprecated:: 0.18
           Use :class:`Devices.from_sys_path` instead.
        rNz>Will be removed in 1.0. Use equivalent Devices method instead.r[)r\)r]r^r_rr)rr rr]r!r!r"r}szDevice.from_sys_pathcCs&ddl}|jdtdd�tj|||�S)zw
        .. versionadded:: 0.5
        .. deprecated:: 0.18
           Use :class:`Devices.from_name` instead.
        rNz>Will be removed in 1.0. Use equivalent Devices method instead.r[)r\)r]r^r_rr,)rr r*r+r]r!r!r"r,�szDevice.from_namecCs&ddl}|jdtdd�tj|||�S)z�
        .. versionadded:: 0.11
        .. deprecated:: 0.18
           Use :class:`Devices.from_device_number` instead.
        rNz>Will be removed in 1.0. Use equivalent Devices method instead.r[)r\)r]r^r_rr/)rr r-r.r]r!r!r"r/�szDevice.from_device_numbercCs$ddl}|jdtdd�tj||�S)z
        .. versionadded:: 0.15
        .. deprecated:: 0.18
           Use :class:`Devices.from_device_file` instead.
        rNz>Will be removed in 1.0. Use equivalent Devices method instead.r[)r\)r]r^r_rr8)rr r4r]r!r!r"r8�szDevice.from_device_filecCs"ddl}|jdtdd�tj|�S)z~
        .. versionadded:: 0.6
        .. deprecated:: 0.18
           Use :class:`Devices.from_environment` instead.
        rNz>Will be removed in 1.0. Use equivalent Devices method instead.r[)r\)r]r^r_rrT)rr r]r!r!r"rT�szDevice.from_environmentcCs||_||_|j|_dS)N)r Z_as_parameter_r$)�selfr Z_devicer!r!r"�__init__�szDevice.__init__cCs|jj|�dS)N)r$Zudev_device_unref)r`r!r!r"�__del__�szDevice.__del__cCs
dj|�S)NzDevice({0.sys_path!r}))�format)r`r!r!r"�__repr__�szDevice.__repr__cCs(|jj|�}|sdSt|j|jj|��S)z_
        The parent :class:`Device` or ``None``, if there is no parent
        device.
        N)r$Zudev_device_get_parentr%r �udev_device_ref)r`�parentr!r!r"rf�sz
Device.parentccs,x&|jj�j|�D]}||kr|VqWdS)a�
        Yield all direct children of this device.

        .. note::

           In udev, parent-child relationships are generally ambiguous, i.e.
           a parent can have multiple children, *and* a child can have multiple
           parents. Hence, `child.parent == parent` does generally *not* hold
           for all `child` objects in `parent.children`. In other words,
           the :attr:`parent` of a device in this property can be different
           from this device!

        .. note::

           As the underlying library does not provide any means to directly
           query the children of a device, this property performs a linear
           search through all devices.

        Return an iterable yielding a :class:`Device` object for each direct
        child of this device.

        .. udevversion:: 172

        .. versionchanged:: 0.13
           Requires udev version 172 now.
        N)r r?Zmatch_parent)r`r&r!r!r"�children�szDevice.childrenccs$|j}x|dk	r|V|j}qWdS)z�
        Yield all ancestors of this device from bottom to top.

        Return an iterator yielding a :class:`Device` object for each
        ancestor of this device from bottom to top.

        .. versionadded:: 0.16
        N)rf)r`rfr!r!r"�	ancestorss

zDevice.ancestorsNcCsDt|�}|dk	rt|�}|jj|||�}|s0dSt|j|jj|��S)a�
        Find the parent device with the given ``subsystem`` and
        ``device_type``.

        ``subsystem`` is a byte or unicode string containing the name of the
        subsystem, in which to search for the parent.  ``device_type`` is a
        byte or unicode string holding the expected device type of the parent.
        It can be ``None`` (the default), which means, that no specific device
        type is expected.

        Return a parent :class:`Device` within the given ``subsystem`` and, if
        ``device_type`` is not ``None``, with the given ``device_type``, or
        ``None``, if this device has no parent device matching these
        constraints.

        .. versionadded:: 0.9
        N)rr$Z-udev_device_get_parent_with_subsystem_devtyper%r re)r`r*r5rfr!r!r"�find_parents
zDevice.find_parentcCsddl}|jdtdd�|jS)a~
        Traverse all parent devices of this device from bottom to top.

        Return an iterable yielding all parent devices as :class:`Device`
        objects, *not* including the current device.  The last yielded
        :class:`Device` is the top of the device hierarchy.

        .. deprecated:: 0.16
           Will be removed in 1.0. Use :attr:`ancestors` instead.
        rNz5Will be removed in 1.0. Use Device.ancestors instead.r[)r\)r]r^r_rh)r`r]r!r!r"�traverse0szDevice.traversecCst|jj|��S)zz
        Absolute path of this device in ``sysfs`` including the ``sysfs``
        mount point as unicode string.
        )rr$Zudev_device_get_syspath)r`r!r!r"rCszDevice.sys_pathcCst|jj|��S)a
        Kernel device path as unicode string.  This path uniquely identifies
        a single device.

        Unlike :attr:`sys_path`, this path does not contain the ``sysfs``
        mount point.  However, the path is absolute and starts with a slash
        ``'/'``.
        )rr$Zudev_device_get_devpath)r`r!r!r"�device_pathLs
zDevice.device_pathcCs |jj|�}|dkrdSt|�S)z�
        Name of the subsystem this device is part of as unicode string.

        :returns: name of subsystem if found, else None
        :rtype: unicode string or NoneType
        N)r$Zudev_device_get_subsystemr)r`Zsubsysr!r!r"r*YszDevice.subsystemcCst|jj|��S)zF
        Device file name inside ``sysfs`` as unicode string.
        )rr$Zudev_device_get_sysname)r`r!r!r"r+dszDevice.sys_namecCs |jj|�}|dk	rt|�SdS)a�
        The trailing number of the :attr:`sys_name` as unicode string, or
        ``None``, if the device has no trailing number in its name.

        .. note::

           The number is returned as unicode string to preserve the exact
           format of the number, especially any leading zeros:

           >>> from pyudev import Context, Device
           >>> context = Context()
           >>> device = Devices.from_path(context, '/sys/devices/LNXSYSTM:00')
           >>> device.sys_number
           u'00'

           To work with numbers, explicitly convert them to ints:

           >>> int(device.sys_number)
           0

        .. versionadded:: 0.11
        N)r$Zudev_device_get_sysnumr)r`r.r!r!r"�
sys_numberlszDevice.sys_numbercCs$|jj|�}|dk	rt|�S|SdS)a�
        Device type as unicode string, or ``None``, if the device type is
        unknown.

        >>> from pyudev import Context
        >>> context = Context()
        >>> for device in context.list_devices(subsystem='net'):
        ...     '{0} - {1}'.format(device.sys_name, device.device_type or 'ethernet')
        ...
        u'eth0 - ethernet'
        u'wlan0 - wlan'
        u'lo - ethernet'
        u'vboxnet0 - ethernet'

        .. versionadded:: 0.10
        N)r$Zudev_device_get_devtyper)r`r5r!r!r"r5�szDevice.device_typecCs |jj|�}|dk	rt|�SdS)z�
        The driver name as unicode string, or ``None``, if there is no
        driver for this device.

        .. versionadded:: 0.5
        N)r$Zudev_device_get_driverr)r`�driverr!r!r"rm�sz
Device.drivercCs |jj|�}|dk	rt|�SdS)a�
        Absolute path to the device node of this device as unicode string or
        ``None``, if this device doesn't have a device node.  The path
        includes the device directory (see :attr:`Context.device_path`).

        This path always points to the actual device node associated with
        this device, and never to any symbolic links to this device node.
        See :attr:`device_links` to get a list of symbolic links to this
        device node.

        .. warning::

           For devices created with :meth:`from_device_file()`, the value of
           this property is not necessary equal to the ``filename`` given to
           :meth:`from_device_file()`.
        N)r$Zudev_device_get_devnoder)r`Znoder!r!r"�device_node�szDevice.device_nodecCs|jj|�S)a
        The device number of the associated device as integer, or ``0``, if no
        device number is associated.

        Use :func:`os.major` and :func:`os.minor` to decompose the device
        number into its major and minor number:

        >>> import os
        >>> from pyudev import Context, Device
        >>> context = Context()
        >>> sda = Devices.from_name(context, 'block', 'sda')
        >>> sda.device_number
        2048L
        >>> (os.major(sda.device_number), os.minor(sda.device_number))
        (8, 0)

        For devices with an associated :attr:`device_node`, this is the same as
        the ``st_rdev`` field of the stat result of the :attr:`device_node`:

        >>> os.stat(sda.device_node).st_rdev
        2048

        .. versionadded:: 0.11
        )r$Zudev_device_get_devnum)r`r!r!r"r6�szDevice.device_numbercCst|jj|��S)ai
        ``True``, if the device is initialized, ``False`` otherwise.

        A device is initialized, if udev has already handled this device and
        has set up device node permissions and context, or renamed a network
        device.

        Consequently, this property is only implemented for devices with a
        device node or for network devices.  On all other devices this property
        is always ``True``.

        It is *not* recommended, that you use uninitialized devices.

        .. seealso:: :attr:`time_since_initialized`

        .. udevversion:: 165

        .. versionadded:: 0.8
        )�boolr$Zudev_device_get_is_initialized)r`r!r!r"�is_initialized�szDevice.is_initializedcCs|jj|�}t|d�S)a�
        The time elapsed since initialization as :class:`~datetime.timedelta`.

        This property is only implemented on devices, which need to store
        properties in the udev database.  On all other devices this property is
        simply zero :class:`~datetime.timedelta`.

        .. seealso:: :attr:`is_initialized`

        .. udevversion:: 165

        .. versionadded:: 0.8
        )�microseconds)r$Z&udev_device_get_usec_since_initializedr	)r`rqr!r!r"�time_since_initialized�szDevice.time_since_initializedccs4|jj|�}x"t|j|�D]\}}t|�VqWdS)a�
        An iterator, which yields the absolute paths (including the device
        directory, see :attr:`Context.device_path`) of all symbolic links
        pointing to the :attr:`device_node` of this device.  The paths are
        unicode strings.

        UDev can create symlinks to the original device node (see
        :attr:`device_node`) inside the device directory.  This is often
        used to assign a constant, fixed device node to devices like
        removeable media, which technically do not have a constant device
        node, or to map a single device into multiple device hierarchies.
        The property provides access to all such symbolic links, which were
        created by UDev for this device.

        .. warning::

           Links are not necessarily resolved by
           :meth:`Devices.from_device_file()`. Hence do *not* rely on
           ``Devices.from_device_file(context, link).device_path ==
           device.device_path`` from any ``link`` in ``device.device_links``.
        N)r$Z#udev_device_get_devlinks_list_entryrr)r`Zdevlinks�namerRr!r!r"�device_linksszDevice.device_linkscCs |jj|�}|dk	rt|�SdS)a
        The device event action as string, or ``None``, if this device was not
        received from a :class:`Monitor`.

        Usual actions are:

        ``'add'``
          A device has been added (e.g. a USB device was plugged in)
        ``'remove'``
          A device has been removed (e.g. a USB device was unplugged)
        ``'change'``
          Something about the device changed (e.g. a device property)
        ``'online'``
          The device is online now
        ``'offline'``
          The device is offline now

        .. warning::

           Though the actions listed above are the most common, this property
           *may* return other values, too, so be prepared to handle unknown
           actions!

        .. versionadded:: 0.16
        N)r$Zudev_device_get_actionr)r`�actionr!r!r"ru sz
Device.actioncCs|jj|�S)z�
        The device event sequence number as integer, or ``0`` if this device
        has no sequence number, i.e. was not received from a :class:`Monitor`.

        .. versionadded:: 0.16
        )r$Zudev_device_get_seqnum)r`r!r!r"�sequence_number>szDevice.sequence_numbercCst|�S)aT
        The system attributes of this device as read-only
        :class:`Attributes` mapping.

        System attributes are basically normal files inside the the device
        directory.  These files contain all sorts of information about the
        device, which may not be reflected by properties.  These attributes
        are commonly used for matching in udev rules, and can be printed
        using ``udevadm info --attribute-walk``.

        The values of these attributes are not always proper strings, and
        can contain arbitrary bytes.

        .. versionadded:: 0.5
        )�
Attributes)r`r!r!r"r:HszDevice.attributescCst|�S)zu
        The udev properties of this object as read-only Properties mapping.

        .. versionadded:: 0.21
        )�
Properties)r`r!r!r"�
properties_szDevice.propertiescCst|�S)a�
        A :class:`Tags` object representing the tags attached to this device.

        The :class:`Tags` object supports a test for a single tag as well as
        iteration over all tags:

        >>> from pyudev import Context
        >>> context = Context()
        >>> device = next(iter(context.list_devices(tag='systemd')))
        >>> 'systemd' in device.tags
        True
        >>> list(device.tags)
        [u'seat', u'systemd', u'uaccess']

        Tags are arbitrary classifiers that can be attached to devices by udev
        scripts and daemons.  For instance, systemd_ uses tags for multi-seat_
        support.

        .. _systemd: http://freedesktop.org/wiki/Software/systemd
        .. _multi-seat: http://www.freedesktop.org/wiki/Software/systemd/multiseat

        .. udevversion:: 154

        .. versionadded:: 0.6

        .. versionchanged:: 0.13
           Return a :class:`Tags` object now.
        )�Tags)r`r!r!r"�tagshszDevice.tagscCs"ddl}|jdtdd�|jj�S)a*
        Iterate over the names of all properties defined for this device.

        Return a generator yielding the names of all properties of this
        device as unicode strings.

        .. deprecated:: 0.21
           Will be removed in 1.0. Access properties with Device.properties.
        rNzAWill be removed in 1.0. Access properties with Device.properties.r[)r\)r]r^r_ry�__iter__)r`r]r!r!r"r|�s
zDevice.__iter__cCs"ddl}|jdtdd�|jj�S)z�
        Return the amount of properties defined for this device as integer.

        .. deprecated:: 0.21
           Will be removed in 1.0. Access properties with Device.properties.
        rNzAWill be removed in 1.0. Access properties with Device.properties.r[)r\)r]r^r_ry�__len__)r`r]r!r!r"r}�szDevice.__len__cCs$ddl}|jdtdd�|jj|�S)a�
        Get the given property from this device.

        ``prop`` is a unicode or byte string containing the name of the
        property.

        Return the property value as unicode string, or raise a
        :exc:`~exceptions.KeyError`, if the given property is not defined
        for this device.

        .. deprecated:: 0.21
           Will be removed in 1.0. Access properties with Device.properties.
        rNzAWill be removed in 1.0. Access properties with Device.properties.r[)r\)r]r^r_ry�__getitem__)r`�propr]r!r!r"r~�szDevice.__getitem__cCs$ddl}|jdtdd�|jj|�S)a
        Get the given property from this device as integer.

        ``prop`` is a unicode or byte string containing the name of the
        property.

        Return the property value as integer. Raise a
        :exc:`~exceptions.KeyError`, if the given property is not defined
        for this device, or a :exc:`~exceptions.ValueError`, if the property
        value cannot be converted to an integer.

        .. deprecated:: 0.21
           Will be removed in 1.0. Use Device.properties.asint() instead.
        rNz<Will be removed in 1.0. Use Device.properties.asint instead.r[)r\)r]r^r_ry�asint)r`rr]r!r!r"r��szDevice.asintcCs$ddl}|jdtdd�|jj|�S)a�
        Get the given property from this device as boolean.

        A boolean property has either a value of ``'1'`` or of ``'0'``,
        where ``'1'`` stands for ``True``, and ``'0'`` for ``False``.  Any
        other value causes a :exc:`~exceptions.ValueError` to be raised.

        ``prop`` is a unicode or byte string containing the name of the
        property.

        Return ``True``, if the property value is ``'1'`` and ``False``, if
        the property value is ``'0'``.  Any other value raises a
        :exc:`~exceptions.ValueError`.  Raise a :exc:`~exceptions.KeyError`,
        if the given property is not defined for this device.

        .. deprecated:: 0.21
           Will be removed in 1.0. Use Device.properties.asbool() instead.
        rNz=Will be removed in 1.0. Use Device.properties.asbool instead.r[)r\)r]r^r_ry�asbool)r`rr]r!r!r"r��sz
Device.asboolcCs
t|j�S)N)�hashrk)r`r!r!r"�__hash__�szDevice.__hash__cCs$t|t�r|j|jkS|j|kSdS)N)�
isinstancer%rk)r`�otherr!r!r"�__eq__�s
z
Device.__eq__cCs$t|t�r|j|jkS|j|kSdS)N)r�r%rk)r`r�r!r!r"�__ne__�s
z
Device.__ne__cCstd��dS)NzDevice not orderable)�	TypeError)r`r�r!r!r"�__gt__sz
Device.__gt__cCstd��dS)NzDevice not orderable)r�)r`r�r!r!r"�__lt__sz
Device.__lt__cCstd��dS)NzDevice not orderable)r�)r`r�r!r!r"�__le__sz
Device.__le__cCstd��dS)NzDevice not orderable)r�)r`r�r!r!r"�__ge__	sz
Device.__ge__)N)1rVrWrXrYrZr#rr,r/r8rTrarbrd�propertyrfrgrhrirjrrkr*r+rlr5rmrnr6rprrrtrurvr:ryr{r|r}r~r�r�r�r�r�r�r�r�r�r!r!r!r"r%MsX
 
	

	 r%c@s@eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dS)rxzN
    udev properties :class:`Device` objects.

    .. versionadded:: 0.21
    cCs||_|j|_dS)N)r&r$)r`r&r!r!r"raszProperties.__init__ccs6|jj|j�}x"t|j|�D]\}}t|�VqWdS)z�
        Iterate over the names of all properties defined for the device.

        Return a generator yielding the names of all properties of this
        device as unicode strings.
        N)r$�%udev_device_get_properties_list_entryr&rr)r`ryrsrRr!r!r"r|szProperties.__iter__cCs(|jj|j�}tdd�t|j|�D��S)zU
        Return the amount of properties defined for this device as integer.
        css|]
}dVqdS)rBNr!)r<rRr!r!r"r>*sz%Properties.__len__.<locals>.<genexpr>)r$r�r&�sumr)r`ryr!r!r"r}$szProperties.__len__cCs,|jj|jt|��}|dkr$t|��t|�S)a9
        Get the given property from this device.

        ``prop`` is a unicode or byte string containing the name of the
        property.

        Return the property value as unicode string, or raise a
        :exc:`~exceptions.KeyError`, if the given property is not defined
        for this device.
        N)r$Zudev_device_get_property_valuer&r�KeyErrorr)r`r�valuer!r!r"r~,s
zProperties.__getitem__cCst||�S)a�
        Get the given property from this device as integer.

        ``prop`` is a unicode or byte string containing the name of the
        property.

        Return the property value as integer. Raise a
        :exc:`~exceptions.KeyError`, if the given property is not defined
        for this device, or a :exc:`~exceptions.ValueError`, if the property
        value cannot be converted to an integer.
        )rN)r`rr!r!r"r�?szProperties.asintcCst||�S)a�
        Get the given property from this device as boolean.

        A boolean property has either a value of ``'1'`` or of ``'0'``,
        where ``'1'`` stands for ``True``, and ``'0'`` for ``False``.  Any
        other value causes a :exc:`~exceptions.ValueError` to be raised.

        ``prop`` is a unicode or byte string containing the name of the
        property.

        Return ``True``, if the property value is ``'1'`` and ``False``, if
        the property value is ``'0'``.  Any other value raises a
        :exc:`~exceptions.ValueError`.  Raise a :exc:`~exceptions.KeyError`,
        if the given property is not defined for this device.
        )r)r`rr!r!r"r�MszProperties.asboolN)
rVrWrXrYrar|r}r~r�r�r!r!r!r"rx
srxc@sNeZdZdZdd�Zedd��Zdd�Zdd	d
�Zdd�Z	d
d�Z
dd�ZdS)rwzQ
    udev attributes for :class:`Device` objects.

    .. versionadded:: 0.5
    cCs||_|j|_dS)N)r&r$)r`r&r!r!r"ragszAttributes.__init__ccsFt|jd�sdS|jj|j�}x"t|j|�D]\}}t|�Vq,WdS)a�
        Yield the ``available`` attributes for the device.

        It is not guaranteed that a key in this list will have a value.
        It is not guaranteed that a key not in this list will not have a value.

        It is guaranteed that the keys in this list are the keys that libudev
        considers to be "available" attributes.

        If libudev version does not define udev_device_get_sysattr_list_entry()
        yields nothing.

        See rhbz#1267584.
        �"udev_device_get_sysattr_list_entryN)�hasattrr$r�r&rr)r`�attrs�	attributerRr!r!r"�available_attributesks
zAttributes.available_attributescCs(|jj|jt|��}|dkr$t|��|S)aD
        Get the given system ``attribute`` for the device.

        :param attribute: the key for an attribute value
        :type attribute: unicode or byte string
        :returns: the value corresponding to ``attribute``
        :rtype: an arbitrary sequence of bytes
        :raises KeyError: if no value found
        N)r$Zudev_device_get_sysattr_valuer&rr�)r`r�r�r!r!r"�_get�s

zAttributes._getNcCs$y
|j|�Stk
r|SXdS)a|
        Get the given system ``attribute`` for the device.

        :param attribute: the key for an attribute value
        :type attribute: unicode or byte string
        :param default: a default if no corresponding value found
        :type default: a sequence of bytes
        :returns: the value corresponding to ``attribute`` or ``default``
        :rtype: object
        N)r�r�)r`r��defaultr!r!r"r;�s
zAttributes.getcCst|j|��S)a�
        Get the given ``attribute`` for the device as unicode string.

        :param attribute: the key for an attribute value
        :type attribute: unicode or byte string
        :returns: the value corresponding to ``attribute``, as unicode
        :rtype: unicode
        :raises KeyError: if no value found for ``attribute``
        :raises UnicodeDecodeError: if value is not convertible
        )rr�)r`r�r!r!r"�asstring�szAttributes.asstringcCst|j|��S)a�
        Get the given ``attribute`` as an int.

        :param attribute: the key for an attribute value
        :type attribute: unicode or byte string
        :returns: the value corresponding to ``attribute``, as an int
        :rtype: int
        :raises KeyError: if no value found for ``attribute``
        :raises UnicodeDecodeError: if value is not convertible to unicode
        :raises ValueError: if unicode value can not be converted to an int
        )rNr�)r`r�r!r!r"r��szAttributes.asintcCst|j|��S)a�
        Get the given ``attribute`` from this device as a bool.

        :param attribute: the key for an attribute value
        :type attribute: unicode or byte string
        :returns: the value corresponding to ``attribute``, as bool
        :rtype: bool
        :raises KeyError: if no value found for ``attribute``
        :raises UnicodeDecodeError: if value is not convertible to unicode
        :raises ValueError: if unicode value can not be converted to a bool

        A boolean attribute has either a value of ``'1'`` or of ``'0'``,
        where ``'1'`` stands for ``True``, and ``'0'`` for ``False``.  Any
        other value causes a :exc:`~exceptions.ValueError` to be raised.
        )rr�)r`r�r!r!r"r��szAttributes.asbool)N)rVrWrXrYrar�r�r�r;r�r�r�r!r!r!r"rw`s

rwc@s0eZdZdZdd�Zdd�Zdd�Zdd	�Zd
S)rzzk
    A iterable over :class:`Device` tags.

    Subclasses the ``Container`` and the ``Iterable`` ABC.
    cCs||_|j|_dS)N)r&r$)r`r&r!r!r"ra�sz
Tags.__init__cs>t|jd�r$t|jj|jt����St�fdd�|D��SdS)z
            Whether ``tag`` exists.

            :param tag: unicode string with name of tag
            :rtype: bool
        �udev_device_has_tagc3s|]}|�kVqdS)Nr!)r<�t)�tagr!r"r>�sz Tags._has_tag.<locals>.<genexpr>N)r�r$ror�r&r�any)r`r�r!)r�r"�_has_tag�sz
Tags._has_tagcCs
|j|�S)z�
        Check for existence of ``tag``.

        ``tag`` is a tag as unicode string.

        Return ``True``, if ``tag`` is attached to the device, ``False``
        otherwise.
        )r�)r`r�r!r!r"�__contains__�s	zTags.__contains__ccs6|jj|j�}x"t|j|�D]\}}t|�VqWdS)zS
        Iterate over all tags.

        Yield each tag as unicode string.
        N)r$Zudev_device_get_tags_list_entryr&rr)r`r{r�rRr!r!r"r|�sz
Tags.__iter__N)rVrWrXrYrar�r�r|r!r!r!r"rz�s

rz)"rYZ
__future__rrrrrrJ�collectionsrrrZdatetimer	Zpyudev.device._errorsr
rrr
rrrZpyudev._utilrrrrr�objectrr%rxrwrzr!r!r!r"�<module>sDESqdevice/__pycache__/__init__.cpython-36.pyc000064400000001307150351420050014374 0ustar003

N�#WO�@s�dZddlmZddlmZddlmZddlmZddlmZddlmZddlm	Z	dd	lm
Z
dd
lmZddlmZdS)
z�
    pyudev.device
    =============

    Device class implementation of :mod:`pyudev`.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
�)�
Attributes)�Device)�Devices)�Tags)�DeviceNotFoundAtPathError)�DeviceNotFoundByFileError)�DeviceNotFoundByNameError)�DeviceNotFoundByNumberError)�DeviceNotFoundError)� DeviceNotFoundInEnvironmentErrorN)
�__doc__Z_devicerrrrZ_errorsrrrr	r
r�r
r
�/usr/lib/python3.6/__init__.py�<module>sdevice/__pycache__/_errors.cpython-36.pyc000064400000014370150351420050014314 0ustar003

5�Vl�@sdZddlmZddlmZddlmZddlmZddlZddlmZeej	�Gdd	�d	e
��Zeej	�Gd
d�de��ZGdd
�d
e�Z
Gdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZGdd�de�ZdS)z�
    pyudev.device._errors
    =====================

    Errors raised by Device methods.

    .. moduleauthor:: Sebastian Wiesner <lunaryorn@gmail.com>
�)�absolute_import)�division)�print_function)�unicode_literalsN)�
add_metaclassc@seZdZdZdS)�DeviceErrorzP
    Any error raised when messing around w/ or trying to discover devices.
    N)�__name__�
__module__�__qualname__�__doc__�rr�/usr/lib/python3.6/_errors.pyr$src@seZdZdZdS)�DeviceNotFoundErrorz�
    An exception indicating that no :class:`Device` was found.

    .. versionchanged:: 0.5
       Rename from ``NoSuchDeviceError`` to its current name.
    N)rr	r
rrrrr
r+src@s,eZdZdZdd�Zedd��Zdd�ZdS)	�DeviceNotFoundAtPathErrorzh
    A :exc:`DeviceNotFoundError` indicating that no :class:`Device` was
    found at a given path.
    cCstj||�dS)N)r�__init__)�self�sys_pathrrr
r;sz"DeviceNotFoundAtPathError.__init__cCs
|jdS)z<
        The path that caused this error as string.
        r)�args)rrrr
r>sz"DeviceNotFoundAtPathError.sys_pathcCsdj|j�S)NzNo device at {0!r})�formatr)rrrr
�__str__Esz!DeviceNotFoundAtPathError.__str__N)rr	r
rr�propertyrrrrrr
r5src@seZdZdZdS)�DeviceNotFoundByFileErrorzp
    A :exc:`DeviceNotFoundError` indicating that no :class:`Device` was
    found from the given filename.
    N)rr	r
rrrrr
rIsrc@seZdZdZdS)�#DeviceNotFoundByInterfaceIndexErrorzw
    A :exc:`DeviceNotFoundError` indicating that no :class:`Device` was found
    from the given interface index.
    N)rr	r
rrrrr
rOsrc@seZdZdZdS)�!DeviceNotFoundByKernelDeviceErrorz�
    A :exc:`DeviceNotFoundError` indicating that no :class:`Device` was found
    from the given kernel device string.

    The format of the kernel device string is defined in the
    systemd.journal-fields man pagees.
    N)rr	r
rrrrr
rUsrc@s8eZdZdZdd�Zedd��Zedd��Zdd	�Zd
S)�DeviceNotFoundByNameErrorzj
    A :exc:`DeviceNotFoundError` indicating that no :class:`Device` was
    found with a given name.
    cCstj|||�dS)N)rr)r�	subsystem�sys_namerrr
resz"DeviceNotFoundByNameError.__init__cCs
|jdS)zA
        The subsystem that caused this error as string.
        r)r)rrrr
rhsz#DeviceNotFoundByNameError.subsystemcCs
|jdS)z@
        The sys name that caused this error as string.
        �)r)rrrr
rosz"DeviceNotFoundByNameError.sys_namecCs
dj|�S)Nz+No device {0.sys_name!r} in {0.subsystem!r})r)rrrr
rvsz!DeviceNotFoundByNameError.__str__N)	rr	r
rrrrrrrrrr
r_s
rc@s8eZdZdZdd�Zedd��Zedd��Zdd	�Zd
S)�DeviceNotFoundByNumberErrorzs
    A :exc:`DeviceNotFoundError` indicating, that no :class:`Device` was found
    for a given device number.
    cCstj|||�dS)N)rr)r�typZnumberrrr
r�sz$DeviceNotFoundByNumberError.__init__cCs
|jdS)zj
        The device type causing this error as string.  Either ``'char'`` or
        ``'block'``.
        r)r)rrrr
�device_type�sz'DeviceNotFoundByNumberError.device_typecCs
|jdS)zB
        The device number causing this error as integer.
        r)r)rrrr
�
device_number�sz)DeviceNotFoundByNumberError.device_numbercCs
dj|�S)Nz7No {0.device_type} device with number {0.device_number})r)rrrr
r�sz#DeviceNotFoundByNumberError.__str__N)	rr	r
rrrr r!rrrrr
rzs
rc@seZdZdZdd�ZdS)� DeviceNotFoundInEnvironmentErrorz�
    A :exc:`DeviceNotFoundError` indicating, that no :class:`Device` could
    be constructed from the process environment.
    cCsdS)NzNo device found in environmentr)rrrr
r�sz(DeviceNotFoundInEnvironmentError.__str__N)rr	r
rrrrrr
r"�sr"c@s&eZdZdZdZddd�Zdd�ZdS)	�DeviceValueErrorz�
    Raised when a parameter has an unacceptable value.

    May also be raised when the parameter has an unacceptable type.
    z+value '%s' for parameter %s is unacceptableNcCs||_||_||_dS)z� Initializer.

            :param object value: the value
            :param str param: the parameter
            :param str msg: an explanatory message
        N)�_value�_param�_msg)r�valueZparam�msgrrr
r�szDeviceValueError.__init__cCs:|jr$|jd}||j|j|jfS|j|j|jfSdS)Nz: %s)r&�_FMT_STRr$r%)rZfmt_strrrr
r�s
zDeviceValueError.__str__)N)rr	r
rr)rrrrrr
r#�s
r#)rZ
__future__rrrr�abcZsixr�ABCMeta�	Exceptionrrrrrrrrr"r#rrrr
�<module>s$	

device/__pycache__/__init__.cpython-36.opt-1.pyc000064400000001307150351420050015333 0ustar003

N�#WO�@s�dZddlmZddlmZddlmZddlmZddlmZddlmZddlm	Z	dd	lm
Z
dd
lmZddlmZdS)
z�
    pyudev.device
    =============

    Device class implementation of :mod:`pyudev`.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
�)�
Attributes)�Device)�Devices)�Tags)�DeviceNotFoundAtPathError)�DeviceNotFoundByFileError)�DeviceNotFoundByNameError)�DeviceNotFoundByNumberError)�DeviceNotFoundError)� DeviceNotFoundInEnvironmentErrorN)
�__doc__Z_devicerrrrZ_errorsrrrr	r
r�r
r
�/usr/lib/python3.6/__init__.py�<module>sdevice/_device.py000064400000126711150351420050007756 0ustar00# -*- coding: utf-8 -*-
# Copyright (C) 2011, 2012 Sebastian Wiesner <lunaryorn@gmail.com>

# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) any later version.

# This library is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
# for more details.

# You should have received a copy of the GNU Lesser General Public License
# along with this library; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA


"""
    pyudev.device._device
    =====================

    Device class implementation of :mod:`pyudev`.

    .. moduleauthor::  Sebastian Wiesner  <lunaryorn@gmail.com>
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import os
import re
from collections import Container
from collections import Iterable
from collections import Mapping
from datetime import timedelta

from pyudev.device._errors import DeviceNotFoundAtPathError
from pyudev.device._errors import DeviceNotFoundByFileError
from pyudev.device._errors import DeviceNotFoundByInterfaceIndexError
from pyudev.device._errors import DeviceNotFoundByKernelDeviceError
from pyudev.device._errors import DeviceNotFoundByNameError
from pyudev.device._errors import DeviceNotFoundByNumberError
from pyudev.device._errors import DeviceNotFoundInEnvironmentError
from pyudev._util import ensure_byte_string
from pyudev._util import ensure_unicode_string
from pyudev._util import get_device_type
from pyudev._util import string_to_bool
from pyudev._util import udev_list_iterate

# pylint: disable=too-many-lines

class Devices(object):
    """
    Class for constructing :class:`Device` objects from various kinds of data.
    """

    @classmethod
    def from_path(cls, context, path):
        """
        Create a device from a device ``path``.  The ``path`` may or may not
        start with the ``sysfs`` mount point:

        >>> from pyudev import Context, Device
        >>> context = Context()
        >>> Devices.from_path(context, '/devices/platform')
        Device(u'/sys/devices/platform')
        >>> Devices.from_path(context, '/sys/devices/platform')
        Device(u'/sys/devices/platform')

        ``context`` is the :class:`Context` in which to search the device.
        ``path`` is a device path as unicode or byte string.

        Return a :class:`Device` object for the device.  Raise
        :exc:`DeviceNotFoundAtPathError`, if no device was found for ``path``.

        .. versionadded:: 0.18
        """
        if not path.startswith(context.sys_path):
            path = os.path.join(context.sys_path, path.lstrip(os.sep))
        return cls.from_sys_path(context, path)

    @classmethod
    def from_sys_path(cls, context, sys_path):
        """
        Create a new device from a given ``sys_path``:

        >>> from pyudev import Context, Device
        >>> context = Context()
        >>> Devices.from_sys_path(context, '/sys/devices/platform')
        Device(u'/sys/devices/platform')

        ``context`` is the :class:`Context` in which to search the device.
        ``sys_path`` is a unicode or byte string containing the path of the
        device inside ``sysfs`` with the mount point included.

        Return a :class:`Device` object for the device.  Raise
        :exc:`DeviceNotFoundAtPathError`, if no device was found for
        ``sys_path``.

        .. versionadded:: 0.18
        """
        device = context._libudev.udev_device_new_from_syspath(
            context, ensure_byte_string(sys_path))
        if not device:
            raise DeviceNotFoundAtPathError(sys_path)
        return Device(context, device)

    @classmethod
    def from_name(cls, context, subsystem, sys_name):
        """
        Create a new device from a given ``subsystem`` and a given
        ``sys_name``:

        >>> from pyudev import Context, Device
        >>> context = Context()
        >>> sda = Devices.from_name(context, 'block', 'sda')
        >>> sda
        Device(u'/sys/devices/pci0000:00/0000:00:1f.2/host0/target0:0:0/0:0:0:0/block/sda')
        >>> sda == Devices.from_path(context, '/block/sda')

        ``context`` is the :class:`Context` in which to search the device.
        ``subsystem`` and ``sys_name`` are byte or unicode strings, which
        denote the subsystem and the name of the device to create.

        Return a :class:`Device` object for the device.  Raise
        :exc:`DeviceNotFoundByNameError`, if no device was found with the given
        name.

        .. versionadded:: 0.18
        """
        sys_name = sys_name.replace("/", "!")
        device = context._libudev.udev_device_new_from_subsystem_sysname(
            context, ensure_byte_string(subsystem),
            ensure_byte_string(sys_name))
        if not device:
            raise DeviceNotFoundByNameError(subsystem, sys_name)
        return Device(context, device)

    @classmethod
    def from_device_number(cls, context, typ, number):
        """
        Create a new device from a device ``number`` with the given device
        ``type``:

        >>> import os
        >>> from pyudev import Context, Device
        >>> ctx = Context()
        >>> major, minor = 8, 0
        >>> device = Devices.from_device_number(context, 'block',
        ...     os.makedev(major, minor))
        >>> device
        Device(u'/sys/devices/pci0000:00/0000:00:11.0/host0/target0:0:0/0:0:0:0/block/sda')
        >>> os.major(device.device_number), os.minor(device.device_number)
        (8, 0)

        Use :func:`os.makedev` to construct a device number from a major and a
        minor device number, as shown in the example above.

        .. warning::

           Device numbers are not unique across different device types.
           Passing a correct number with a wrong type may silently yield a
           wrong device object, so make sure to pass the correct device type.

        ``context`` is the :class:`Context`, in which to search the device.
        ``type`` is either ``'char'`` or ``'block'``, according to whether the
        device is a character or block device.  ``number`` is the device number
        as integer.

        Return a :class:`Device` object for the device with the given device
        ``number``.  Raise :exc:`DeviceNotFoundByNumberError`, if no device was
        found with the given device type and number.

        .. versionadded:: 0.18
        """
        device = context._libudev.udev_device_new_from_devnum(
            context, ensure_byte_string(typ[0]), number)
        if not device:
            raise DeviceNotFoundByNumberError(typ, number)
        return Device(context, device)

    @classmethod
    def from_device_file(cls, context, filename):
        """
        Create a new device from the given device file:

        >>> from pyudev import Context, Device
        >>> context = Context()
        >>> device = Devices.from_device_file(context, '/dev/sda')
        >>> device
        Device(u'/sys/devices/pci0000:00/0000:00:0d.0/host2/target2:0:0/2:0:0:0/block/sda')
        >>> device.device_node
        u'/dev/sda'

        .. warning::

           Though the example seems to suggest that ``device.device_node ==
           filename`` holds with ``device = Devices.from_device_file(context,
           filename)``, this is only true in a majority of cases.  There *can*
           be devices, for which this relation is actually false!  Thus, do
           *not* expect :attr:`~Device.device_node` to be equal to the given
           ``filename`` for the returned :class:`Device`.  Especially, use
           :attr:`~Device.device_node` if you need the device file of a
           :class:`Device` created with this method afterwards.

        ``context`` is the :class:`Context` in which to search the device.
        ``filename`` is a string containing the path of a device file.

        Return a :class:`Device` representing the given device file.  Raise
        :exc:`DeviceNotFoundByFileError` if ``filename`` is no device file
        at all or if ``filename`` does not exist or if its metadata was
        inaccessible.

        .. versionadded:: 0.18
        """
        try:
            device_type = get_device_type(filename)
            device_number = os.stat(filename).st_rdev
        except (EnvironmentError, ValueError) as err:
            raise DeviceNotFoundByFileError(err)

        return cls.from_device_number(context, device_type, device_number)


    @classmethod
    def from_interface_index(cls, context, ifindex):
        """
        Locate a device based on the interface index.

        :param `Context` context: the libudev context
        :param int ifindex: the interface index
        :returns: the device corresponding to the interface index
        :rtype: `Device`

        This method is only appropriate for network devices.
        """
        network_devices = context.list_devices(subsystem='net')
        dev = next(
           (d for d in network_devices if \
              d.attributes.get('ifindex') == ifindex),
           None
        )
        if dev is not None:
            return dev
        else:
            raise DeviceNotFoundByInterfaceIndexError(ifindex)


    @classmethod
    def from_kernel_device(cls, context, kernel_device):
        """
        Locate a device based on the kernel device.

        :param `Context` context: the libudev context
        :param str kernel_device: the kernel device
        :returns: the device corresponding to ``kernel_device``
        :rtype: `Device`
        """
        switch_char = kernel_device[0]
        rest = kernel_device[1:]
        if switch_char in ('b', 'c'):
            number_re = re.compile(r'^(?P<major>\d+):(?P<minor>\d+)$')
            match = number_re.match(rest)
            if match:
                number = os.makedev(
                   int(match.group('major')),
                   int(match.group('minor'))
                )
                return cls.from_device_number(context, switch_char, number)
            else:
                raise DeviceNotFoundByKernelDeviceError(kernel_device)
        elif switch_char == 'n':
            return cls.from_interface_index(context, rest)
        elif switch_char == '+':
            (subsystem, _, kernel_device_name) = rest.partition(':')
            if kernel_device_name and subsystem:
                return cls.from_name(context, subsystem, kernel_device_name)
            else:
                raise DeviceNotFoundByKernelDeviceError(kernel_device)
        else:
            raise DeviceNotFoundByKernelDeviceError(kernel_device)


    @classmethod
    def from_environment(cls, context):
        """
        Create a new device from the process environment (as in
        :data:`os.environ`).

        This only works reliable, if the current process is called from an
        udev rule, and is usually used for tools executed from ``IMPORT=``
        rules.  Use this method to create device objects in Python scripts
        called from udev rules.

        ``context`` is the library :class:`Context`.

        Return a :class:`Device` object constructed from the environment.
        Raise :exc:`DeviceNotFoundInEnvironmentError`, if no device could be
        created from the environment.

        .. udevversion:: 152

        .. versionadded:: 0.18
        """
        device = context._libudev.udev_device_new_from_environment(context)
        if not device:
            raise DeviceNotFoundInEnvironmentError()
        return Device(context, device)

    @classmethod
    def METHODS(cls): # pylint: disable=invalid-name
        """
        Return methods that obtain a :class:`Device` from a variety of
        different data.

        :return: a list of from_* methods.
        :rtype: list of class methods

        .. versionadded:: 0.18
        """
        return [ #pragma: no cover
           cls.from_device_file,
           cls.from_device_number,
           cls.from_name,
           cls.from_path,
           cls.from_sys_path
        ]


class Device(Mapping):
    # pylint: disable=too-many-public-methods
    """
    A single device with attached attributes and properties.

    This class subclasses the ``Mapping`` ABC, providing a read-only
    dictionary mapping property names to the corresponding values.
    Therefore all well-known dicitionary methods and operators
    (e.g. ``.keys()``, ``.items()``, ``in``) are available to access device
    properties.

    Aside of the properties, a device also has a set of udev-specific
    attributes like the path inside ``sysfs``.

    :class:`Device` objects compare equal and unequal to other devices and
    to strings (based on :attr:`device_path`).  However, there is no
    ordering on :class:`Device` objects, and the corresponding operators
    ``>``, ``<``, ``<=`` and ``>=`` raise :exc:`~exceptions.TypeError`.

    .. warning::

       **Never** use object identity (``is`` operator) to compare
       :class:`Device` objects.  :mod:`pyudev` may create multiple
       :class:`Device` objects for the same device.  Instead compare
       devices by value using ``==`` or ``!=``.

    :class:`Device` objects are hashable and can therefore be used as keys
    in dictionaries and sets.

    They can also be given directly as ``udev_device *`` to functions wrapped
    through :mod:`ctypes`.
    """

    @classmethod
    def from_path(cls, context, path): #pragma: no cover
        """
        .. versionadded:: 0.4
        .. deprecated:: 0.18
           Use :class:`Devices.from_path` instead.
        """
        import warnings
        warnings.warn(
           'Will be removed in 1.0. Use equivalent Devices method instead.',
           DeprecationWarning,
           stacklevel=2
        )
        return Devices.from_path(context, path)

    @classmethod
    def from_sys_path(cls, context, sys_path): #pragma: no cover
        """
        .. versionchanged:: 0.4
           Raise :exc:`NoSuchDeviceError` instead of returning ``None``, if
           no device was found for ``sys_path``.
        .. versionchanged:: 0.5
           Raise :exc:`DeviceNotFoundAtPathError` instead of
           :exc:`NoSuchDeviceError`.
        .. deprecated:: 0.18
           Use :class:`Devices.from_sys_path` instead.
        """
        import warnings
        warnings.warn(
           'Will be removed in 1.0. Use equivalent Devices method instead.',
           DeprecationWarning,
           stacklevel=2
        )
        return Devices.from_sys_path(context, sys_path)

    @classmethod
    def from_name(cls, context, subsystem, sys_name): #pragma: no cover
        """
        .. versionadded:: 0.5
        .. deprecated:: 0.18
           Use :class:`Devices.from_name` instead.
        """
        import warnings
        warnings.warn(
           'Will be removed in 1.0. Use equivalent Devices method instead.',
           DeprecationWarning,
           stacklevel=2
        )
        return Devices.from_name(context, subsystem, sys_name)

    @classmethod
    def from_device_number(cls, context, typ, number): #pragma: no cover
        """
        .. versionadded:: 0.11
        .. deprecated:: 0.18
           Use :class:`Devices.from_device_number` instead.
        """
        import warnings
        warnings.warn(
           'Will be removed in 1.0. Use equivalent Devices method instead.',
           DeprecationWarning,
           stacklevel=2
        )
        return Devices.from_device_number(context, typ, number)

    @classmethod
    def from_device_file(cls, context, filename): #pragma: no cover
        """
        .. versionadded:: 0.15
        .. deprecated:: 0.18
           Use :class:`Devices.from_device_file` instead.
        """
        import warnings
        warnings.warn(
           'Will be removed in 1.0. Use equivalent Devices method instead.',
           DeprecationWarning,
           stacklevel=2
        )
        return Devices.from_device_file(context, filename)

    @classmethod
    def from_environment(cls, context): #pragma: no cover
        """
        .. versionadded:: 0.6
        .. deprecated:: 0.18
           Use :class:`Devices.from_environment` instead.
        """
        import warnings
        warnings.warn(
           'Will be removed in 1.0. Use equivalent Devices method instead.',
           DeprecationWarning,
           stacklevel=2
        )
        return Devices.from_environment(context)

    def __init__(self, context, _device):
        self.context = context
        self._as_parameter_ = _device
        self._libudev = context._libudev

    def __del__(self):
        self._libudev.udev_device_unref(self)

    def __repr__(self):
        return 'Device({0.sys_path!r})'.format(self)

    @property
    def parent(self):
        """
        The parent :class:`Device` or ``None``, if there is no parent
        device.
        """
        parent = self._libudev.udev_device_get_parent(self)
        if not parent:
            return None
        # the parent device is not referenced, thus forcibly acquire a
        # reference
        return Device(self.context, self._libudev.udev_device_ref(parent))

    @property
    def children(self):
        """
        Yield all direct children of this device.

        .. note::

           In udev, parent-child relationships are generally ambiguous, i.e.
           a parent can have multiple children, *and* a child can have multiple
           parents. Hence, `child.parent == parent` does generally *not* hold
           for all `child` objects in `parent.children`. In other words,
           the :attr:`parent` of a device in this property can be different
           from this device!

        .. note::

           As the underlying library does not provide any means to directly
           query the children of a device, this property performs a linear
           search through all devices.

        Return an iterable yielding a :class:`Device` object for each direct
        child of this device.

        .. udevversion:: 172

        .. versionchanged:: 0.13
           Requires udev version 172 now.
        """
        for device in self.context.list_devices().match_parent(self):
            if device != self:
                yield device

    @property
    def ancestors(self):
        """
        Yield all ancestors of this device from bottom to top.

        Return an iterator yielding a :class:`Device` object for each
        ancestor of this device from bottom to top.

        .. versionadded:: 0.16
        """
        parent = self.parent
        while parent is not None:
            yield parent
            parent = parent.parent

    def find_parent(self, subsystem, device_type=None):
        """
        Find the parent device with the given ``subsystem`` and
        ``device_type``.

        ``subsystem`` is a byte or unicode string containing the name of the
        subsystem, in which to search for the parent.  ``device_type`` is a
        byte or unicode string holding the expected device type of the parent.
        It can be ``None`` (the default), which means, that no specific device
        type is expected.

        Return a parent :class:`Device` within the given ``subsystem`` and, if
        ``device_type`` is not ``None``, with the given ``device_type``, or
        ``None``, if this device has no parent device matching these
        constraints.

        .. versionadded:: 0.9
        """
        subsystem = ensure_byte_string(subsystem)
        if device_type is not None:
            device_type = ensure_byte_string(device_type)
        parent = self._libudev.udev_device_get_parent_with_subsystem_devtype(
            self, subsystem, device_type)
        if not parent:
            return None
        # parent device is not referenced, thus forcibly acquire a reference
        return Device(self.context, self._libudev.udev_device_ref(parent))

    def traverse(self):
        """
        Traverse all parent devices of this device from bottom to top.

        Return an iterable yielding all parent devices as :class:`Device`
        objects, *not* including the current device.  The last yielded
        :class:`Device` is the top of the device hierarchy.

        .. deprecated:: 0.16
           Will be removed in 1.0. Use :attr:`ancestors` instead.
        """
        import warnings
        warnings.warn(
           'Will be removed in 1.0. Use Device.ancestors instead.',
           DeprecationWarning,
           stacklevel=2
        )
        return self.ancestors

    @property
    def sys_path(self):
        """
        Absolute path of this device in ``sysfs`` including the ``sysfs``
        mount point as unicode string.
        """
        return ensure_unicode_string(
            self._libudev.udev_device_get_syspath(self))

    @property
    def device_path(self):
        """
        Kernel device path as unicode string.  This path uniquely identifies
        a single device.

        Unlike :attr:`sys_path`, this path does not contain the ``sysfs``
        mount point.  However, the path is absolute and starts with a slash
        ``'/'``.
        """
        return ensure_unicode_string(
            self._libudev.udev_device_get_devpath(self))

    @property
    def subsystem(self):
        """
        Name of the subsystem this device is part of as unicode string.

        :returns: name of subsystem if found, else None
        :rtype: unicode string or NoneType
        """
        subsys = self._libudev.udev_device_get_subsystem(self)
        return None if subsys is None else ensure_unicode_string(subsys)

    @property
    def sys_name(self):
        """
        Device file name inside ``sysfs`` as unicode string.
        """
        return ensure_unicode_string(
            self._libudev.udev_device_get_sysname(self))

    @property
    def sys_number(self):
        """
        The trailing number of the :attr:`sys_name` as unicode string, or
        ``None``, if the device has no trailing number in its name.

        .. note::

           The number is returned as unicode string to preserve the exact
           format of the number, especially any leading zeros:

           >>> from pyudev import Context, Device
           >>> context = Context()
           >>> device = Devices.from_path(context, '/sys/devices/LNXSYSTM:00')
           >>> device.sys_number
           u'00'

           To work with numbers, explicitly convert them to ints:

           >>> int(device.sys_number)
           0

        .. versionadded:: 0.11
        """
        number = self._libudev.udev_device_get_sysnum(self)
        return ensure_unicode_string(number) if number is not None else None

    @property
    def device_type(self):
        """
        Device type as unicode string, or ``None``, if the device type is
        unknown.

        >>> from pyudev import Context
        >>> context = Context()
        >>> for device in context.list_devices(subsystem='net'):
        ...     '{0} - {1}'.format(device.sys_name, device.device_type or 'ethernet')
        ...
        u'eth0 - ethernet'
        u'wlan0 - wlan'
        u'lo - ethernet'
        u'vboxnet0 - ethernet'

        .. versionadded:: 0.10
        """
        device_type = self._libudev.udev_device_get_devtype(self)
        if device_type is not None:
            return ensure_unicode_string(device_type)
        else:
            return device_type

    @property
    def driver(self):
        """
        The driver name as unicode string, or ``None``, if there is no
        driver for this device.

        .. versionadded:: 0.5
        """
        driver = self._libudev.udev_device_get_driver(self)
        return ensure_unicode_string(driver) if driver is not None else None

    @property
    def device_node(self):
        """
        Absolute path to the device node of this device as unicode string or
        ``None``, if this device doesn't have a device node.  The path
        includes the device directory (see :attr:`Context.device_path`).

        This path always points to the actual device node associated with
        this device, and never to any symbolic links to this device node.
        See :attr:`device_links` to get a list of symbolic links to this
        device node.

        .. warning::

           For devices created with :meth:`from_device_file()`, the value of
           this property is not necessary equal to the ``filename`` given to
           :meth:`from_device_file()`.
        """
        node = self._libudev.udev_device_get_devnode(self)
        return ensure_unicode_string(node) if node is not None else None

    @property
    def device_number(self):
        """
        The device number of the associated device as integer, or ``0``, if no
        device number is associated.

        Use :func:`os.major` and :func:`os.minor` to decompose the device
        number into its major and minor number:

        >>> import os
        >>> from pyudev import Context, Device
        >>> context = Context()
        >>> sda = Devices.from_name(context, 'block', 'sda')
        >>> sda.device_number
        2048L
        >>> (os.major(sda.device_number), os.minor(sda.device_number))
        (8, 0)

        For devices with an associated :attr:`device_node`, this is the same as
        the ``st_rdev`` field of the stat result of the :attr:`device_node`:

        >>> os.stat(sda.device_node).st_rdev
        2048

        .. versionadded:: 0.11
        """
        return self._libudev.udev_device_get_devnum(self)

    @property
    def is_initialized(self):
        """
        ``True``, if the device is initialized, ``False`` otherwise.

        A device is initialized, if udev has already handled this device and
        has set up device node permissions and context, or renamed a network
        device.

        Consequently, this property is only implemented for devices with a
        device node or for network devices.  On all other devices this property
        is always ``True``.

        It is *not* recommended, that you use uninitialized devices.

        .. seealso:: :attr:`time_since_initialized`

        .. udevversion:: 165

        .. versionadded:: 0.8
        """
        return bool(self._libudev.udev_device_get_is_initialized(self))

    @property
    def time_since_initialized(self):
        """
        The time elapsed since initialization as :class:`~datetime.timedelta`.

        This property is only implemented on devices, which need to store
        properties in the udev database.  On all other devices this property is
        simply zero :class:`~datetime.timedelta`.

        .. seealso:: :attr:`is_initialized`

        .. udevversion:: 165

        .. versionadded:: 0.8
        """
        microseconds = self._libudev.udev_device_get_usec_since_initialized(
            self)
        return timedelta(microseconds=microseconds)

    @property
    def device_links(self):
        """
        An iterator, which yields the absolute paths (including the device
        directory, see :attr:`Context.device_path`) of all symbolic links
        pointing to the :attr:`device_node` of this device.  The paths are
        unicode strings.

        UDev can create symlinks to the original device node (see
        :attr:`device_node`) inside the device directory.  This is often
        used to assign a constant, fixed device node to devices like
        removeable media, which technically do not have a constant device
        node, or to map a single device into multiple device hierarchies.
        The property provides access to all such symbolic links, which were
        created by UDev for this device.

        .. warning::

           Links are not necessarily resolved by
           :meth:`Devices.from_device_file()`. Hence do *not* rely on
           ``Devices.from_device_file(context, link).device_path ==
           device.device_path`` from any ``link`` in ``device.device_links``.
        """
        devlinks = self._libudev.udev_device_get_devlinks_list_entry(self)
        for name, _ in udev_list_iterate(self._libudev, devlinks):
            yield ensure_unicode_string(name)

    @property
    def action(self):
        """
        The device event action as string, or ``None``, if this device was not
        received from a :class:`Monitor`.

        Usual actions are:

        ``'add'``
          A device has been added (e.g. a USB device was plugged in)
        ``'remove'``
          A device has been removed (e.g. a USB device was unplugged)
        ``'change'``
          Something about the device changed (e.g. a device property)
        ``'online'``
          The device is online now
        ``'offline'``
          The device is offline now

        .. warning::

           Though the actions listed above are the most common, this property
           *may* return other values, too, so be prepared to handle unknown
           actions!

        .. versionadded:: 0.16
        """
        action = self._libudev.udev_device_get_action(self)
        return ensure_unicode_string(action) if action is not None else None

    @property
    def sequence_number(self):
        """
        The device event sequence number as integer, or ``0`` if this device
        has no sequence number, i.e. was not received from a :class:`Monitor`.

        .. versionadded:: 0.16
        """
        return self._libudev.udev_device_get_seqnum(self)

    @property
    def attributes(self):
        """
        The system attributes of this device as read-only
        :class:`Attributes` mapping.

        System attributes are basically normal files inside the the device
        directory.  These files contain all sorts of information about the
        device, which may not be reflected by properties.  These attributes
        are commonly used for matching in udev rules, and can be printed
        using ``udevadm info --attribute-walk``.

        The values of these attributes are not always proper strings, and
        can contain arbitrary bytes.

        .. versionadded:: 0.5
        """
        # do *not* cache the created object in an attribute of this class.
        # Doing so creates an uncollectable reference cycle between Device and
        # Attributes, because Attributes refers to this object through
        # Attributes.device.
        return Attributes(self)

    @property
    def properties(self):
        """
        The udev properties of this object as read-only Properties mapping.

        .. versionadded:: 0.21
        """
        return Properties(self)

    @property
    def tags(self):
        """
        A :class:`Tags` object representing the tags attached to this device.

        The :class:`Tags` object supports a test for a single tag as well as
        iteration over all tags:

        >>> from pyudev import Context
        >>> context = Context()
        >>> device = next(iter(context.list_devices(tag='systemd')))
        >>> 'systemd' in device.tags
        True
        >>> list(device.tags)
        [u'seat', u'systemd', u'uaccess']

        Tags are arbitrary classifiers that can be attached to devices by udev
        scripts and daemons.  For instance, systemd_ uses tags for multi-seat_
        support.

        .. _systemd: http://freedesktop.org/wiki/Software/systemd
        .. _multi-seat: http://www.freedesktop.org/wiki/Software/systemd/multiseat

        .. udevversion:: 154

        .. versionadded:: 0.6

        .. versionchanged:: 0.13
           Return a :class:`Tags` object now.
        """
        return Tags(self)

    def __iter__(self):
        """
        Iterate over the names of all properties defined for this device.

        Return a generator yielding the names of all properties of this
        device as unicode strings.

        .. deprecated:: 0.21
           Will be removed in 1.0. Access properties with Device.properties.
        """
        import warnings
        warnings.warn(
           'Will be removed in 1.0. Access properties with Device.properties.',
           DeprecationWarning,
           stacklevel=2
        )
        return self.properties.__iter__()

    def __len__(self):
        """
        Return the amount of properties defined for this device as integer.

        .. deprecated:: 0.21
           Will be removed in 1.0. Access properties with Device.properties.
        """
        import warnings
        warnings.warn(
           'Will be removed in 1.0. Access properties with Device.properties.',
           DeprecationWarning,
           stacklevel=2
        )
        return self.properties.__len__()

    def __getitem__(self, prop):
        """
        Get the given property from this device.

        ``prop`` is a unicode or byte string containing the name of the
        property.

        Return the property value as unicode string, or raise a
        :exc:`~exceptions.KeyError`, if the given property is not defined
        for this device.

        .. deprecated:: 0.21
           Will be removed in 1.0. Access properties with Device.properties.
        """
        import warnings
        warnings.warn(
           'Will be removed in 1.0. Access properties with Device.properties.',
           DeprecationWarning,
           stacklevel=2
        )
        return self.properties.__getitem__(prop)

    def asint(self, prop):
        """
        Get the given property from this device as integer.

        ``prop`` is a unicode or byte string containing the name of the
        property.

        Return the property value as integer. Raise a
        :exc:`~exceptions.KeyError`, if the given property is not defined
        for this device, or a :exc:`~exceptions.ValueError`, if the property
        value cannot be converted to an integer.

        .. deprecated:: 0.21
           Will be removed in 1.0. Use Device.properties.asint() instead.
        """
        import warnings
        warnings.warn(
           'Will be removed in 1.0. Use Device.properties.asint instead.',
           DeprecationWarning,
           stacklevel=2
        )
        return self.properties.asint(prop)

    def asbool(self, prop):
        """
        Get the given property from this device as boolean.

        A boolean property has either a value of ``'1'`` or of ``'0'``,
        where ``'1'`` stands for ``True``, and ``'0'`` for ``False``.  Any
        other value causes a :exc:`~exceptions.ValueError` to be raised.

        ``prop`` is a unicode or byte string containing the name of the
        property.

        Return ``True``, if the property value is ``'1'`` and ``False``, if
        the property value is ``'0'``.  Any other value raises a
        :exc:`~exceptions.ValueError`.  Raise a :exc:`~exceptions.KeyError`,
        if the given property is not defined for this device.

        .. deprecated:: 0.21
           Will be removed in 1.0. Use Device.properties.asbool() instead.
        """
        import warnings
        warnings.warn(
           'Will be removed in 1.0. Use Device.properties.asbool instead.',
           DeprecationWarning,
           stacklevel=2
        )
        return self.properties.asbool(prop)

    def __hash__(self):
        return hash(self.device_path)

    def __eq__(self, other):
        if isinstance(other, Device):
            return self.device_path == other.device_path
        else:
            return self.device_path == other

    def __ne__(self, other):
        if isinstance(other, Device):
            return self.device_path != other.device_path
        else:
            return self.device_path != other

    def __gt__(self, other):
        raise TypeError('Device not orderable')

    def __lt__(self, other):
        raise TypeError('Device not orderable')

    def __le__(self, other):
        raise TypeError('Device not orderable')

    def __ge__(self, other):
        raise TypeError('Device not orderable')


class Properties(Mapping):
    """
    udev properties :class:`Device` objects.

    .. versionadded:: 0.21
    """

    def __init__(self, device):
        self.device = device
        self._libudev = device._libudev

    def __iter__(self):
        """
        Iterate over the names of all properties defined for the device.

        Return a generator yielding the names of all properties of this
        device as unicode strings.
        """
        properties = \
           self._libudev.udev_device_get_properties_list_entry(self.device)
        for name, _ in udev_list_iterate(self._libudev, properties):
            yield ensure_unicode_string(name)

    def __len__(self):
        """
        Return the amount of properties defined for this device as integer.
        """
        properties = \
           self._libudev.udev_device_get_properties_list_entry(self.device)
        return sum(1 for _ in udev_list_iterate(self._libudev, properties))

    def __getitem__(self, prop):
        """
        Get the given property from this device.

        ``prop`` is a unicode or byte string containing the name of the
        property.

        Return the property value as unicode string, or raise a
        :exc:`~exceptions.KeyError`, if the given property is not defined
        for this device.
        """
        value = self._libudev.udev_device_get_property_value(
           self.device,
           ensure_byte_string(prop)
        )
        if value is None:
            raise KeyError(prop)
        return ensure_unicode_string(value)

    def asint(self, prop):
        """
        Get the given property from this device as integer.

        ``prop`` is a unicode or byte string containing the name of the
        property.

        Return the property value as integer. Raise a
        :exc:`~exceptions.KeyError`, if the given property is not defined
        for this device, or a :exc:`~exceptions.ValueError`, if the property
        value cannot be converted to an integer.
        """
        return int(self[prop])

    def asbool(self, prop):
        """
        Get the given property from this device as boolean.

        A boolean property has either a value of ``'1'`` or of ``'0'``,
        where ``'1'`` stands for ``True``, and ``'0'`` for ``False``.  Any
        other value causes a :exc:`~exceptions.ValueError` to be raised.

        ``prop`` is a unicode or byte string containing the name of the
        property.

        Return ``True``, if the property value is ``'1'`` and ``False``, if
        the property value is ``'0'``.  Any other value raises a
        :exc:`~exceptions.ValueError`.  Raise a :exc:`~exceptions.KeyError`,
        if the given property is not defined for this device.
        """
        return string_to_bool(self[prop])


class Attributes(object):
    """
    udev attributes for :class:`Device` objects.

    .. versionadded:: 0.5
    """

    def __init__(self, device):
        self.device = device
        self._libudev = device._libudev

    @property
    def available_attributes(self):
        """
        Yield the ``available`` attributes for the device.

        It is not guaranteed that a key in this list will have a value.
        It is not guaranteed that a key not in this list will not have a value.

        It is guaranteed that the keys in this list are the keys that libudev
        considers to be "available" attributes.

        If libudev version does not define udev_device_get_sysattr_list_entry()
        yields nothing.

        See rhbz#1267584.
        """
        if not hasattr(self._libudev, 'udev_device_get_sysattr_list_entry'):
            return # pragma: no cover
        attrs = self._libudev.udev_device_get_sysattr_list_entry(self.device)
        for attribute, _ in udev_list_iterate(self._libudev, attrs):
            yield ensure_unicode_string(attribute)

    def _get(self, attribute):
        """
        Get the given system ``attribute`` for the device.

        :param attribute: the key for an attribute value
        :type attribute: unicode or byte string
        :returns: the value corresponding to ``attribute``
        :rtype: an arbitrary sequence of bytes
        :raises KeyError: if no value found
        """
        value = self._libudev.udev_device_get_sysattr_value(
           self.device,
           ensure_byte_string(attribute)
        )
        if value is None:
            raise KeyError(attribute)
        return value

    def get(self, attribute, default=None):
        """
        Get the given system ``attribute`` for the device.

        :param attribute: the key for an attribute value
        :type attribute: unicode or byte string
        :param default: a default if no corresponding value found
        :type default: a sequence of bytes
        :returns: the value corresponding to ``attribute`` or ``default``
        :rtype: object
        """
        try:
            return self._get(attribute)
        except KeyError:
            return default

    def asstring(self, attribute):
        """
        Get the given ``attribute`` for the device as unicode string.

        :param attribute: the key for an attribute value
        :type attribute: unicode or byte string
        :returns: the value corresponding to ``attribute``, as unicode
        :rtype: unicode
        :raises KeyError: if no value found for ``attribute``
        :raises UnicodeDecodeError: if value is not convertible
        """
        return ensure_unicode_string(self._get(attribute))

    def asint(self, attribute):
        """
        Get the given ``attribute`` as an int.

        :param attribute: the key for an attribute value
        :type attribute: unicode or byte string
        :returns: the value corresponding to ``attribute``, as an int
        :rtype: int
        :raises KeyError: if no value found for ``attribute``
        :raises UnicodeDecodeError: if value is not convertible to unicode
        :raises ValueError: if unicode value can not be converted to an int
        """
        return int(self.asstring(attribute))

    def asbool(self, attribute):
        """
        Get the given ``attribute`` from this device as a bool.

        :param attribute: the key for an attribute value
        :type attribute: unicode or byte string
        :returns: the value corresponding to ``attribute``, as bool
        :rtype: bool
        :raises KeyError: if no value found for ``attribute``
        :raises UnicodeDecodeError: if value is not convertible to unicode
        :raises ValueError: if unicode value can not be converted to a bool

        A boolean attribute has either a value of ``'1'`` or of ``'0'``,
        where ``'1'`` stands for ``True``, and ``'0'`` for ``False``.  Any
        other value causes a :exc:`~exceptions.ValueError` to be raised.
        """
        return string_to_bool(self.asstring(attribute))


class Tags(Iterable, Container):
    """
    A iterable over :class:`Device` tags.

    Subclasses the ``Container`` and the ``Iterable`` ABC.
    """

    # pylint: disable=too-few-public-methods

    def __init__(self, device):
        self.device = device
        self._libudev = device._libudev

    def _has_tag(self, tag):
        """
            Whether ``tag`` exists.

            :param tag: unicode string with name of tag
            :rtype: bool
        """
        if hasattr(self._libudev, 'udev_device_has_tag'):
            return bool(self._libudev.udev_device_has_tag(
                self.device, ensure_byte_string(tag)))
        else: # pragma: no cover
            return any(t == tag for t in self)

    def __contains__(self, tag):
        """
        Check for existence of ``tag``.

        ``tag`` is a tag as unicode string.

        Return ``True``, if ``tag`` is attached to the device, ``False``
        otherwise.
        """
        return self._has_tag(tag)

    def __iter__(self):
        """
        Iterate over all tags.

        Yield each tag as unicode string.
        """
        tags = self._libudev.udev_device_get_tags_list_entry(self.device)
        for tag, _ in udev_list_iterate(self._libudev, tags):
            yield ensure_unicode_string(tag)