Beispiel #1
0
def delete_last_lines(n):
    if 'LINUX' in platform_system().upper():
        for _ in range(n):
            sys_stdout.write(LINUX_CURSOR_UP_ONE)
            sys_stdout.write(LINUX_ERASE_LINE)
    elif 'WINDOWS' in platform_system().upper():
        os_system('cls')
Beispiel #2
0
def getProbeParams():
    """
    create probe parameters list based on OS type, by default if no command given uses ping command, if -T given uses traceroute command,
    if -C command give, then runs probe using this command
    """
    global defaultCommand  #reference global defaultCommand variable
    global TRACE
    global hostIndex

    if 'LINUX' in platform_system().upper():
        # -c number of pings, -i interval between pings, -W timeout sec
        if USERCOMMAND == '' and TRACE == False:  #default action to run ping command
            defaultCommand = [
                'ping', '-c', '1', '-W', '{}'.format(PROBETIMEOUT / 1000),
                '{target}'
            ]  #last item will be replaced with IP or name
        elif TRACE == True:  #if -T given, run traceroute command
            defaultCommand = ['traceroute', '{target}'
                              ]  #last item will be replaced with IP or name
        else:  #means that command been given, hence need to run it
            defaultCommand = [
                item for item in USERCOMMAND.split(' ') if item != ''
            ]  #list comprehension to loop over items and skip empty items
            #check if no {target} position been given on command, hence have to append it to the end:
            if '{target}' not in defaultCommand:
                defaultCommand.append('{target}')
        hostIndex = defaultCommand.index('{target}')

    elif 'WINDOWS' in platform_system().upper():
        # -n numer of pings, -w timeout ms
        if USERCOMMAND == '' and TRACE == False:
            defaultCommand = [
                'ping', '-n', '1', '-w',
                str(PROBETIMEOUT), '{target}'
            ]  #last item will be replaced with IP or name
        elif TRACE == True:  #if -T given, run traceroute command
            defaultCommand = [
                'tracert', '-d', '-w',
                str(PROBETIMEOUT), '{target}'
            ]  #last item will be replaced with IP or name
        else:  #means that command been given, hence need to run it
            defaultCommand = [
                item for item in USERCOMMAND.split(' ') if item != ''
            ]  #list comprehension to loop over items and skip empty items
            #check if no {target} position been given on command, hence have to append it to the end:
            if '{target}' not in defaultCommand:
                defaultCommand.append('{target}')
        hostIndex = defaultCommand.index('{target}')

    else:
        raise SystemExit('ERROR: Unsupported OS, nor Windows nor Linux')
Beispiel #3
0
def visualizer(solution, size_rows, size_cols):
    master = Tk()
    canvas_width = (GUI_BOX_SIZE * size_cols) + GUI_BOX_SPACING
    canvas_height = (GUI_BOX_SIZE * size_rows) + GUI_BOX_SPACING
    canvas = Canvas(master,
                    width=canvas_width + 1,
                    height=canvas_height + 1,
                    bg=GUI_COLOR_2,
                    borderwidth=0,
                    highlightthickness=0)
    canvas.pack()
    item_matrix = gui_item_matrix(canvas, size_rows, size_cols)
    master.bind('<Escape>', gui_close)
    master.bind('<Q>', gui_close)
    master.bind('<q>', gui_close)
    master.bind(
        '<r>', lambda i: gui_refresh(master, canvas, item_matrix, solution,
                                     size_rows, size_cols))
    master.after(0, gui_replay, master, canvas, item_matrix, solution,
                 size_rows, size_cols)
    if platform_system() == 'Darwin':
        system(
            '''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "'''
            + basename(executable) + '''" to true' ''')
    master.mainloop()
Beispiel #4
0
    def _locate_cuda_libdir(self):
        '''
        Locate the "standard" CUDA SDK library directory in the local
        file system. Supports 64-Bit Windows, Linux and Mac OS X.
        In case the caller supplied cuda_libdir in the constructor
        other than None that value is returned unchecked, else a
        best-effort attempt is made.
        Precedence:
            Windows: cuda_libdir > %CUDA_PATH%
            Linux:   cuda_libdir > $CUDA_ROOT > $LD_LIBRARY_PATH > '/usr/lib/x86_64-linux-gnu'
        Returns a pair (libdir, libptn) where libdir is None in case
            of failure or a string containing the absolute path of the
            directory, and libptn is the %-format pattern to construct
            library file names from library names on the local system.
        Raises a RuntimeError in case of failure.
        Links:
        - Post-installation Actions
          http://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html#post-installation-actions
        TODO:
        - Is $CUDA_ROOT/lib64 the correct path to assume for 64-Bit CUDA libraries on Linux?
        - Mac OS X (Darwin) is currently treated like Linux, is that correct?
        - Check CMake's FindCUDA module, it might contain some helpful clues in its sources
          https://cmake.org/cmake/help/v3.0/module/FindCUDA.html
          https://github.com/Kitware/CMake/blob/master/Modules/FindCUDA.cmake
        - Verify all Linux code paths somehow
        '''
        from os.path import isfile, join
        from platform import system as platform_system
        system = platform_system()
        libdir, libptn = None, None
        if system == 'Windows':
            if self.cuda_libdir is not None:
                libdir = self.cuda_libdir
            elif 'CUDA_PATH' in os.environ and isfile(join(os.environ['CUDA_PATH'], 'lib\\x64\\cudadevrt.lib')):
                libdir = join(os.environ['CUDA_PATH'], 'lib\\x64')
            libptn = '%s.lib'
        elif system in ['Linux', 'Darwin']:
            if self.cuda_libdir is not None:
                libdir = self.cuda_libdir
            elif 'CUDA_ROOT' in os.environ and isfile(join(os.environ['CUDA_ROOT'], 'lib64/libcudadevrt.a')):
                libdir = join(os.environ['CUDA_ROOT'], 'lib64')
            elif 'LD_LIBRARY_PATH' in os.environ:
                for ld_path in os.environ['LD_LIBRARY_PATH'].split(':'):
                    if isfile(join(ld_path, 'libcudadevrt.a')):
                        libdir = ld_path
                        break

            if libdir is None and isfile('/usr/lib/x86_64-linux-gnu/libcudadevrt.a'):
                libdir = '/usr/lib/x86_64-linux-gnu'

            if libdir is None:
                nvcc_path = _find_nvcc_on_path()
                if nvcc_path is not None:
                    libdir = join(os.path.dirname(nvcc_path), "..", "lib64")

            libptn = 'lib%s.a'
        if libdir is None:
            raise RuntimeError('Unable to locate the CUDA SDK installation '
                'directory, set CUDA library path manually')
        return libdir, libptn
Beispiel #5
0
def main():
    """
    Starts UI Inspector.

    Arguments:
        - None

    Returns:
        - None
    """

    try:
        x_old, y_old = None, None
        while True:
            x, y = uisoup.mouse.get_position()
            if (x, y) != (x_old, y_old):
                x_old, y_old = x, y
                obj_element = uisoup.get_object_by_coordinates(x, y)
                clear_command = \
                    'cls' if platform_system() == 'Windows' else 'clear'
                printable_data = \
                    UIInspector.get_current_element_info(obj_element)
                system(clear_command)
                print printable_data
            sleep(0.5)
    except KeyboardInterrupt:
        system('cls')
Beispiel #6
0
def visualizer(solution, puzzle_size):
    master = Tk()
    canvas_width = (GUI_BOX_SIZE * puzzle_size) + GUI_BOX_SPACING
    canvas_height = (GUI_BOX_SIZE * puzzle_size) + GUI_BOX_SPACING
    canvas = Canvas(
        master,
        width=canvas_width + 1,
        height=canvas_height + 1,
        bg=GUI_COLOR_2,
        borderwidth=0,
        highlightthickness=0,
    )
    canvas.pack()
    item_matrix = gui_item_matrix(canvas, puzzle_size)
    master.bind("<Escape>", gui_close)
    master.bind("<Q>", gui_close)
    master.bind("<q>", gui_close)
    master.after(0, gui_replay, master, canvas, item_matrix, solution, puzzle_size)
    if platform_system() == "Darwin":
        system(
            '''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "'''
            + basename(executable)
            + """" to true' """
        )
    master.mainloop()
Beispiel #7
0
    def __init__(self, device=None, config_path=None, user_path=".", cmd_line=""):
        """
        Create an option object and check that parameters are valid.

        :param device: The device to use
        :type device: str
        :param config_path: The openzwave config directory. If None, try to configure automatically.
        :type config_path: str
        :param user_path: The user directory
        :type user_path: str
        :param cmd_line: The "command line" options of the openzwave library
        :type cmd_line: str

        """
        if platform_system() == 'Windows':
            self._device = device
        else:
            #For linux
            try:
                if os.path.exists(device):
                    if os.access(device, os.R_OK) and os.access(device, os.W_OK):
                        self._device = device
                    else:
                        import sys, traceback
                        raise ZWaveException(u"Can't write to device %s : %s" % (device, traceback.format_exception(*sys.exc_info())))
                else:
                    import sys, traceback
                    raise ZWaveException(u"Can't find device %s : %s" % (device, traceback.format_exception(*sys.exc_info())))
            except:
                import sys, traceback
                raise ZWaveException(u"Error when retrieving device %s : %s" % (device, traceback.format_exception(*sys.exc_info())))
        libopenzwave.PyOptions.__init__(self, config_path=config_path, user_path=user_path, cmd_line=cmd_line)
        self._user_path = user_path
        self._config_path = config_path
Beispiel #8
0
def main():
    """
    Starts UI Inspector.

    Arguments:
        - None

    Returns:
        - None
    """

    try:
        x_old, y_old = None, None
        while True:
            x, y = uisoup.mouse.get_position()
            if (x, y) != (x_old, y_old):
                x_old, y_old = x, y
                obj_element = uisoup.get_object_by_coordinates(x, y)
                clear_command = \
                    'cls' if platform_system() == 'Windows' else 'clear'
                printable_data = \
                    UIInspector.get_current_element_info(obj_element)
                system(clear_command)
                print printable_data
            sleep(0.5)
    except KeyboardInterrupt:
        system('cls')
def get_background_cmd(photo_name: str):
    system = platform_system()
    if system == 'Darwin':
        raise ValueError(
            'macOS is not yet implemented to change the background. However, you can still change the background. photo name: {}'.format(
                photo_name))
    elif system == 'Linux':
        logging.info('Linux OS found; finding distro')
        dist = distro_name()
        logging.info('Found {}'.format(dist))
        if 'elementary' in dist or 'Ubuntu' in dist:
            return [
                'gsettings',
                'set',
                'org.gnome.desktop.background',
                'picture-uri',
                'file://' + photo_name
            ]
        elif not run('feh --help > /dev/null'): # Actually true, 0 (success) is cast to false.
            logging.info('Found Feh')
            return [
                'feh',
                '--bg-scale',
                photo_name
            ]

    elif system == 'Windows':
        raise ValueError(
            'Windows is not yet implemented to change the background. However, you can still change the background. photo name: {}'.format(
                photo_name))
    raise ValueError(
        '{} is not yet implemented to change the background. However, you can still change the background. photo name: {}'.format(
            system, photo_name))
Beispiel #10
0
    def test_inheritance(self):
        # Make sure the inheritance hierarchy matches the documentation
        exc_set = set()
        for object_ in builtins.__dict__.values():
            try:
                if issubclass(object_, BaseException):
                    exc_set.add(object_.__name__)
            except TypeError:
                pass

        inheritance_tree = open(os.path.join(os.path.split(__file__)[0],
                                                'exception_hierarchy.txt'))
        try:
            superclass_name = inheritance_tree.readline().rstrip()
            try:
                last_exc = getattr(builtins, superclass_name)
            except AttributeError:
                self.fail("base class %s not a built-in" % superclass_name)
            self.assertIn(superclass_name, exc_set,
                          '%s not found' % superclass_name)
            exc_set.discard(superclass_name)
            superclasses = []  # Loop will insert base exception
            last_depth = 0
            for exc_line in inheritance_tree:
                exc_line = exc_line.rstrip()
                depth = exc_line.rindex('-')
                exc_name = exc_line[depth+2:]  # Slice past space
                if '(' in exc_name:
                    paren_index = exc_name.index('(')
                    platform_name = exc_name[paren_index+1:-1]
                    exc_name = exc_name[:paren_index-1]  # Slice off space
                    if platform_system() != platform_name:
                        exc_set.discard(exc_name)
                        continue
                if '[' in exc_name:
                    left_bracket = exc_name.index('[')
                    exc_name = exc_name[:left_bracket-1]  # cover space
                try:
                    exc = getattr(builtins, exc_name)
                except AttributeError:
                    self.fail("%s not a built-in exception" % exc_name)
                if last_depth < depth:
                    superclasses.append((last_depth, last_exc))
                elif last_depth > depth:
                    while superclasses[-1][0] >= depth:
                        superclasses.pop()
                self.assertTrue(issubclass(exc, superclasses[-1][1]),
                "%s is not a subclass of %s" % (exc.__name__,
                    superclasses[-1][1].__name__))
                try:  # Some exceptions require arguments; just skip them
                    self.verify_instance_interface(exc())
                except TypeError:
                    pass
                self.assertIn(exc_name, exc_set)
                exc_set.discard(exc_name)
                last_exc = exc
                last_depth = depth
        finally:
            inheritance_tree.close()
        self.assertEqual(len(exc_set), 0, "%s not accounted for" % exc_set)
Beispiel #11
0
def turbulenz_sdk_version(sdk_version):
    query = turbulenz_api(sdk_version)

    if query.get('ok', False):
        data = query.get('data', None)
        if data:
            os_mapping = {
                'Windows': 'windows',
                'Linux': 'linux',
                'Darwin': 'mac'
            }
            sysname = platform_system()
            os = os_mapping[sysname]
            this_os = data[os]
            latest_version = this_os['latest']
            all_versions = this_os['versions']
            if all_versions:
                latest_link = 'https://hub.turbulenz.com/download/%s' % \
                    all_versions[latest_version]['file']
            else:
                latest_link = ''
                latest_version = ''

            return {
                'newest': latest_version,
                'current': SDK_VERSION,
                'download': latest_link
            }

    return {
        'newest': '',
        'current': SDK_VERSION,
        'download': ''
    }
Beispiel #12
0
    def __init__(self, device=None, config_path=None, user_path=None, cmd_line=None):
        """
        Create an option object and check that parameters are valid.

        :param device: The device to use
        :type device: str
        :param config_path: The openzwave config directory. If None, try to configure automatically.
        :type config_path: str
        :param user_path: The user directory
        :type user_path: str
        :param cmd_line: The "command line" options of the openzwave library
        :type cmd_line: str

        """
        if platform_system() == 'Windows':
            self._device = device
        else:
            #For linux
            try:
                if os.path.exists(device):
                    if os.access(device, os.R_OK) and os.access(device, os.W_OK):
                        self._device = device
                    else:
                        import sys, traceback
                        raise ZWaveException(u"Can't write to device %s : %s" % (device, traceback.format_exception(*sys.exc_info())))
                else:
                    import sys, traceback
                    raise ZWaveException(u"Can't find device %s : %s" % (device, traceback.format_exception(*sys.exc_info())))
            except:
                import sys, traceback
                raise ZWaveException(u"Error when retrieving device %s : %s" % (device, traceback.format_exception(*sys.exc_info())))
        libopenzwave.PyOptions.__init__(self, config_path=config_path, user_path=user_path, cmd_line=cmd_line)
Beispiel #13
0
        def get_ip_mac_pinged(ip):
            """
                Returns a list  [ip,mac,pinged]
            """
            pinged = True
            mac = None
            sock = QTcpSocket()
            sock.connectToHost(ip, 80)
            sock.close()

            #ARP
            if pinged == True:
                if platform_system() == "Windows":
                    CREATE_NO_WINDOW = 0x08000000
                    arpexit = subprocess.check_output(
                        ["arp", "-a", ip], creationflags=CREATE_NO_WINDOW)
                    for s in arpexit.split(b" "):
                        if len(s) == 17 and s.find(b"-") != -1:
                            mac = s.decode().replace("-", ":").upper()
                else:
                    arpexit = subprocess.check_output(["arp", ip])
                    for s in arpexit.decode('utf-8').split(" "):
                        if len(s) == 17 and s.find(":") != -1:
                            mac = s.upper()
            return (ip, mac, pinged)
Beispiel #14
0
def turbulenz_sdk_version(sdk_version):
    query = turbulenz_api(sdk_version)

    if query.get('ok', False):
        data = query.get('data', None)
        if data:
            os_mapping = {
                'Windows': 'windows',
                'Linux': 'linux',
                'Darwin': 'mac'
            }
            sysname = platform_system()
            os = os_mapping[sysname]
            this_os = data[os]
            latest_version = this_os['latest']
            all_versions = this_os['versions']
            if all_versions:
                latest_link = 'https://hub.turbulenz.com/download/%s' % \
                    all_versions[latest_version]['file']
            else:
                latest_link = ''
                latest_version = ''

            return {
                'newest': latest_version,
                'current': SDK_VERSION,
                'download': latest_link
            }

    return {
        'newest': '',
        'current': SDK_VERSION,
        'download': ''
    }
Beispiel #15
0
 def run(self):
     if platform_system() == "Linux":
         os.system("rm -Rf {}/swapping_ebuilds*".format(
             site.getsitepackages()[0]))
         os.system("rm /usr/bin/swapping_ebuilds")
     else:
         print(_("Uninstall command only works in Linux"))
Beispiel #16
0
    def test_inheritance(self):
        # Make sure the inheritance hierarchy matches the documentation
        exc_set = set()
        for object_ in builtins.__dict__.values():
            try:
                if issubclass(object_, BaseException):
                    exc_set.add(object_.__name__)
            except TypeError:
                pass

        inheritance_tree = open(os.path.join(os.path.split(__file__)[0],
                                                'exception_hierarchy.txt'))
        try:
            superclass_name = inheritance_tree.readline().rstrip()
            try:
                last_exc = getattr(builtins, superclass_name)
            except AttributeError:
                self.fail("base class %s not a built-in" % superclass_name)
            self.assertIn(superclass_name, exc_set,
                          '%s not found' % superclass_name)
            exc_set.discard(superclass_name)
            superclasses = []  # Loop will insert base exception
            last_depth = 0
            for exc_line in inheritance_tree:
                exc_line = exc_line.rstrip()
                depth = exc_line.rindex('-')
                exc_name = exc_line[depth+2:]  # Slice past space
                if '(' in exc_name:
                    paren_index = exc_name.index('(')
                    platform_name = exc_name[paren_index+1:-1]
                    exc_name = exc_name[:paren_index-1]  # Slice off space
                    if platform_system() != platform_name:
                        exc_set.discard(exc_name)
                        continue
                if '[' in exc_name:
                    left_bracket = exc_name.index('[')
                    exc_name = exc_name[:left_bracket-1]  # cover space
                try:
                    exc = getattr(builtins, exc_name)
                except AttributeError:
                    self.fail("%s not a built-in exception" % exc_name)
                if last_depth < depth:
                    superclasses.append((last_depth, last_exc))
                elif last_depth > depth:
                    while superclasses[-1][0] >= depth:
                        superclasses.pop()
                self.assertTrue(issubclass(exc, superclasses[-1][1]),
                "%s is not a subclass of %s" % (exc.__name__,
                    superclasses[-1][1].__name__))
                try:  # Some exceptions require arguments; just skip them
                    self.verify_instance_interface(exc())
                except TypeError:
                    pass
                self.assertIn(exc_name, exc_set)
                exc_set.discard(exc_name)
                last_exc = exc
                last_depth = depth
        finally:
            inheritance_tree.close()
        self.assertEqual(len(exc_set), 0, "%s not accounted for" % exc_set)
Beispiel #17
0
 def test_inheritance(self):
     # Make sure the inheritance hierarchy matches the documentation
     exc_set = set(x for x in dir(exceptions) if not x.startswith('_'))
     inheritance_tree = open(
         os.path.join(
             os.path.split(__file__)[0], 'exception_hierarchy.txt'))
     try:
         superclass_name = inheritance_tree.readline().rstrip()
         try:
             last_exc = getattr(__builtin__, superclass_name)
         except AttributeError:
             self.fail("base class %s not a built-in" % superclass_name)
         self.failUnless(superclass_name in exc_set)
         exc_set.discard(superclass_name)
         superclasses = []  # Loop will insert base exception
         last_depth = 0
         for exc_line in inheritance_tree:
             exc_line = exc_line.rstrip()
             depth = exc_line.rindex('-')
             exc_name = exc_line[depth + 2:]  # Slice past space
             if '(' in exc_name:
                 paren_index = exc_name.index('(')
                 platform_name = exc_name[paren_index + 1:-1]
                 exc_name = exc_name[:paren_index - 1]  # Slice off space
                 if platform_system() != platform_name:
                     exc_set.discard(exc_name)
                     continue
             if '[' in exc_name:
                 left_bracket = exc_name.index('[')
                 exc_name = exc_name[:left_bracket - 1]  # cover space
             try:
                 exc = getattr(__builtin__, exc_name)
             except AttributeError:
                 # This exception is only compiled into Stackless.
                 if self.stackless_enabled() or exc_name != "TaskletExit":
                     self.fail("%s not a built-in exception" % exc_name)
             if last_depth < depth:
                 superclasses.append((last_depth, last_exc))
             elif last_depth > depth:
                 while superclasses[-1][0] >= depth:
                     superclasses.pop()
             self.failUnless(
                 issubclass(exc, superclasses[-1][1]),
                 "%s is not a subclass of %s" %
                 (exc.__name__, superclasses[-1][1].__name__))
             try:  # Some exceptions require arguments; just skip them
                 self.verify_instance_interface(exc())
             except TypeError:
                 pass
             # This exception is only compiled into Stackless.
             if self.stackless_enabled() or exc_name != "TaskletExit":
                 self.failUnless(exc_name in exc_set)
             exc_set.discard(exc_name)
             last_exc = exc
             last_depth = depth
     finally:
         inheritance_tree.close()
     self.failUnlessEqual(len(exc_set), 0, "%s not accounted for" % exc_set)
Beispiel #18
0
 def run(self):
     if platform_system() == "Linux":
         os.system("rm -Rf {}/mymoviebook*".format(
             site.getsitepackages()[0]))
         os.system("rm /usr/bin/mymoviebook")
         os.system("rm /usr/share/man/man1/mymoviebook.1")
         os.system("rm /usr/share/man/es/man1/mymoviebook.1")
     else:
         print(_("Uninstall command only works in Linux"))
Beispiel #19
0
 def test_inheritance(self):
     # Make sure the inheritance hierarchy matches the documentation
     exc_set = set(x for x in dir(exceptions) if not x.startswith('_'))
     inheritance_tree = open(os.path.join(os.path.split(__file__)[0],
                                             'exception_hierarchy.txt'))
     try:
         superclass_name = inheritance_tree.readline().rstrip()
         try:
             last_exc = getattr(__builtin__, superclass_name)
         except AttributeError:
             self.fail("base class %s not a built-in" % superclass_name)
         self.failUnless(superclass_name in exc_set)
         exc_set.discard(superclass_name)
         superclasses = []  # Loop will insert base exception
         last_depth = 0
         for exc_line in inheritance_tree:
             exc_line = exc_line.rstrip()
             depth = exc_line.rindex('-')
             exc_name = exc_line[depth+2:]  # Slice past space
             if '(' in exc_name:
                 paren_index = exc_name.index('(')
                 platform_name = exc_name[paren_index+1:-1]
                 exc_name = exc_name[:paren_index-1]  # Slice off space
                 if platform_system() != platform_name:
                     exc_set.discard(exc_name)
                     continue
             if '[' in exc_name:
                 left_bracket = exc_name.index('[')
                 exc_name = exc_name[:left_bracket-1]  # cover space
             try:
                 exc = getattr(__builtin__, exc_name)
             except AttributeError:
                 # This exception is only compiled into Stackless.
                 if self.stackless_enabled() or exc_name != "TaskletExit":
                     self.fail("%s not a built-in exception" % exc_name)
             if last_depth < depth:
                 superclasses.append((last_depth, last_exc))
             elif last_depth > depth:
                 while superclasses[-1][0] >= depth:
                     superclasses.pop()
             self.failUnless(issubclass(exc, superclasses[-1][1]),
             "%s is not a subclass of %s" % (exc.__name__,
                 superclasses[-1][1].__name__))
             try:  # Some exceptions require arguments; just skip them
                 self.verify_instance_interface(exc())
             except TypeError:
                 pass
             # This exception is only compiled into Stackless.
             if self.stackless_enabled() or exc_name != "TaskletExit":
                 self.failUnless(exc_name in exc_set)
             exc_set.discard(exc_name)
             last_exc = exc
             last_depth = depth
     finally:
         inheritance_tree.close()
     self.failUnlessEqual(len(exc_set), 0, "%s not accounted for" % exc_set)
Beispiel #20
0
def main_console():
    from devicesinlan.libdevicesinlan import MemConsole
    mem = MemConsole()
    signal.signal(signal.SIGINT, mem.signal_handler)
    mem.setQApplication()
    mem.setLanguage()
    mem.setInstallationUUID()
    mem.parse_args()
    if platform_system() == "Windows":
        press_key_to_continue()
Beispiel #21
0
    def _set_icon(self, window):

        from platform import system as platform_system

        window.iconbitmap({
            'Windows':
            os.path.join(os.getcwd(), 'misc', 'icon_main.ico'),
            'Linux':
            '@' + os.path.join(os.getcwd(), 'misc', 'icon_main.xbm')
        }[platform_system()])
Beispiel #22
0
def print_sysinfo():
    """Osnovne informacije o Pythonu i računalu"""
    out ="<table>"
    out += "<tr><td><strong>Python verzija</strong></td><td>{}</td></tr>".format(python_version())
    out += "<tr><td><strong>kompajler</strong></td><td>{}</td></tr>".format(python_compiler())
    out += "<tr><td><strong>sustav</strong></td><td>{}</td></tr>".format(platform_system())
    out += "<tr><td><strong>broj CPU-a</strong></td><td>{}</td></tr>".format(cpu_count())
    out += "<tr><td><strong>interpreter</strong></td><td>{}</td></tr>".format(architecture()[0])
    out += "</table>"
    return out
Beispiel #23
0
 def setInstallationUUID(self):
     if self.settings.value("frmMain/uuid", "None") == "None":
         self.settings.setValue("frmMain/uuid", str(uuid4()))
     url = 'http://devicesinlan.sourceforge.net/php/devicesinlan_installations.php?uuid={}&version={}&platform={}'.format(
         self.settings.value("frmMain/uuid"), __version__,
         platform_system())
     try:
         web = b2s(urlopen(url).read())
     except:
         web = self.tr("Error collecting statistics")
     logging.debug("{}, answering {}".format(web, url))
Beispiel #24
0
def printImportError(ex):
    platform = platform_system()
    print(
        "IMPORT ERROR: One or more Python packages are not available in your environment."
    )
    print("Missing package: '{0}'\n".format(ex.name))
    if (platform == "Windows"):
        print("Run: 'py.exe -3 -m pip install -r requirements.txt'\n")
    elif (platform == "Linux"):
        print("Run: 'python3 -m pip install -r requirements.txt'\n")
    exit(1)
Beispiel #25
0
def putty_connection(name):
    current_os, device = platform_system(), retrieve(Device, name=name)
    username, password, _ = get_credentials(device)
    if current_os == 'Windows':
        path_putty = join(current_app.path, 'applications', 'putty.exe')
        ssh = f'{path_putty} -ssh {username}@{device.ip_address} -pw {password}'
        Popen(ssh.split())
    else:
        sshpass = f'"sshpass -p {password} ssh {username}@{device.ip_address}"'
        os_system(f'gnome-terminal -- /bin/bash -c {sshpass}')
    return jsonify({'success': True})
Beispiel #26
0
 def GetTerminalSize():
     """Returns the terminal size as tuple (width, height) for Windows, Mac OS (Darwin), Linux, cygwin (Windows), MinGW32/64 (Windows)."""
     platform = platform_system()
     if (platform == "Windows"):
         size = Terminal.__GetTerminalSizeOnWindows()
     elif ((platform in ["Linux", "Darwin"])
           or platform.startswith("CYGWIN")
           or platform.startswith("MINGW32")
           or platform.startswith("MINGW64")):
         size = Terminal.__GetTerminalSizeOnLinux()
     if (size is None):
         size = (80, 25)  # default size
     return size
Beispiel #27
0
def print_sysinfo():
    """Osnovne informacije o Pythonu i računalu"""
    out = "<table>"
    out += "<tr><td><strong>Python verzija</strong></td><td>{}</td></tr>".format(
        python_version())
    out += "<tr><td><strong>kompajler</strong></td><td>{}</td></tr>".format(
        python_compiler())
    out += "<tr><td><strong>sustav</strong></td><td>{}</td></tr>".format(
        platform_system())
    out += "<tr><td><strong>broj CPU-a</strong></td><td>{}</td></tr>".format(
        cpu_count())
    out += "<tr><td><strong>interpreter</strong></td><td>{}</td></tr>".format(
        architecture()[0])
    out += "</table>"
    return out
Beispiel #28
0
def putty_connection(name):
    current_os, node = platform_system(), get_obj(Node, name=name)
    password = cisco_type7.decode(current_user.password)
    if current_os == 'Windows':
        path_putty = join(current_app.path, 'applications', 'putty.exe')
        ssh_connection = '{} -ssh {}@{} -pw {}'.format(path_putty,
                                                       current_user.name,
                                                       node.ip_address,
                                                       password)
        Popen(ssh_connection.split())
    else:
        arg = "gnome-terminal -e 'bash -c \"sshpass -p {} ssh {}@{}\"'".format(
            password, current_user.name, node.ip_address)
        os_system(arg)
    return jsonify({'success': True})
Beispiel #29
0
def is_port_taken(port, is_linux=platform_system().lower() == 'linux'):
    # Short for Linux so as not to bind to a socket which in turn means waiting until it's closed by OS
    if is_linux:
        for conn in psutil.net_connections(kind='tcp'):
            if conn.laddr[1] == port and conn.status == psutil.CONN_LISTEN:
                return True
    else:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            sock.bind(('', port))
            sock.close()
        except socket.error as e:
            if e[0] == errno.EADDRINUSE:
                return True
            raise
Beispiel #30
0
def create_background_process(command_list, log_file):
    kwargs = {}
    if platform_system() == 'Windows':  # on windows
        CREATE_NEW_PROCESS_GROUP = 0x00000200
        DETACHED_PROCESS = 0x00000008
        kwargs.update(creationflags=DETACHED_PROCESS
                      | CREATE_NEW_PROCESS_GROUP)
    else:  # on UNIX
        kwargs.update(start_new_session=True)

    # if (app.config["DEBUG"]):
    with open(log_file, "wb") as log:
        p = Popen(command_list, stdin=PIPE, stdout=log, stderr=log, **kwargs)
    # else:
    #     p = Popen(command_list, stdin=PIPE, stdout=PIPE, stderr=PIPE, **kwargs)
    assert not p.poll()
Beispiel #31
0
    def __init__(self):
        self.platform = platform_system()
        self.client_id = None
        self.channel = None
        self.modules = []
        self.queue_send = Queue.Queue()
        self.queue_recv = Queue.Queue()
        self.events = {}

        # Used for debug only, you should hardcode those credentials to avoid external dependencies
        self.settings = {}

        # Logging information
        aptpy_logger = logging.getLogger('aptpy')
        aptpy_logger.setLevel(logging.DEBUG)

        # Create a rotation logging, so we won't have and endless file
        if DEBUG:
            rotate = logging.handlers.RotatingFileHandler('aptpy.log',
                                                          maxBytes=(5 * 1024 *
                                                                    1024),
                                                          backupCount=3)
            rotate.setLevel(logging.DEBUG)
            rotate.setFormatter(
                logging.Formatter('%(asctime)s|%(levelname)-8s| %(message)s',
                                  '%Y-%m-%d %H:%M:%S'))

            aptpy_logger.addHandler(rotate)

            try:
                with open('settings.json', 'rb') as handle:
                    self.settings = json.load(handle)
            except IOError:
                pass

        console = logging.StreamHandler()
        console.setLevel(logging.DEBUG)

        console.setFormatter(
            logging.Formatter("%(asctime)s|%(levelname)-8s| %(message)s",
                              '%Y-%m-%d %H:%M:%S'))
        aptpy_logger.addHandler(console)

        aptpy_logger.disabled = True

        if DEBUG:
            aptpy_logger.disabled = False
Beispiel #32
0
def get_terminal_size():
    """ getTerminalSize()
     - get width and height of console
     - works on linux,os x,windows,cygwin(windows)
     originally retrieved from:
     http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python
    """
    current_os = platform_system()
    tuple_xy = None
    if current_os == 'Windows':
        tuple_xy = _get_terminal_size_windows()
        if tuple_xy is None:
            tuple_xy = _get_terminal_size_tput()
            # needed for window's python in cygwin's xterm!
    if current_os in ['Linux', 'Darwin'] or current_os.startswith('CYGWIN'):
        tuple_xy = _get_terminal_size_linux()
    if tuple_xy is None:
        print "default"
        tuple_xy = (80, 25)      # default value
    return tuple_xy
Beispiel #33
0
    def load_tblSoftware(self):
        self.tblSoftware.setItem(0, 0, qright(colorama__version__))
        self.tblSoftware.setItem(0, 1,
                                 qleft("https://github.com/tartley/colorama"))

        self.tblSoftware.setItem(1, 0, qright(PYQT_VERSION_STR))
        self.tblSoftware.setItem(
            1, 1, qleft("https://riverbankcomputing.com/software/pyqt/intro"))

        self.tblSoftware.setItem(2, 0, qright(python_version()))
        self.tblSoftware.setItem(2, 1, qleft("https://www.python.org"))

        if platform_system() == "Windows":
            self.tblSoftware.setItem(3, 0, qright(VERSION))
        else:
            self.tblSoftware.setItem(3, 0, qright(scapy__version__[:-1]))
        self.tblSoftware.setItem(3, 1,
                                 qleft("https://github.com/secdev/scapy"))

        self.tblSoftware.applySettings()
Beispiel #34
0
def win_term():
    """
    set the Windows console to understand the ANSI color codes
    """
    from platform import system as platform_system

    if platform_system() == "Windows":
        import ctypes

        kernel32 = ctypes.windll.kernel32

        # https://docs.microsoft.com/en-us/windows/console/setconsolemode
        STD_OUTPUT_HANDLE = -11
        ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004

        mode = ctypes.wintypes.DWORD()
        if kernel32.GetConsoleMode(kernel32.GetStdHandle(STD_OUTPUT_HANDLE),
                                   ctypes.byref(mode)):
            mode = mode.value | ENABLE_VIRTUAL_TERMINAL_PROCESSING
            kernel32.SetConsoleMode(kernel32.GetStdHandle(STD_OUTPUT_HANDLE),
                                    mode)
Beispiel #35
0
def get_available_memory(include_swap=True):
    """Retrieve available memory

    Parameters
    ----------
    include_swap : bool
        Include available swap in the calculation.

    Returns
    -------
    available : number
        The amount available.
    """
    system = platform_system()

    # Apple MacOS
    log.debug(f'Running OS is "{system}"')
    if system in ['Darwin']:
        return get_available_memory_darwin(include_swap=include_swap)

    # Default to Linux-like:
    return get_available_memory_linux(include_swap=include_swap)
Beispiel #36
0
def press_key_to_continue():
    if platform_system() == "Windows":
        system("pause")
    else:
        s = _("Press a key to continue...")
        system("read -p '{}'".format(s))
Beispiel #37
0
def main():
    py_ver = {}

    # check OS
    if platform_system() != 'Windows':
        print('Error: This script is only used on Windows.')
        sys.exit(1)

    # process sys.argv using argparse
    parser = argparse.ArgumentParser(description='Launch script with the Python version defined in the hashbang.')
    parser.add_argument('-s', '--setup', action='store_true', dest='setup',
                        help='Configure Python install paths')
    group = parser.add_mutually_exclusive_group()
    group.add_argument('-i', '--idle', action='store_true', dest='idle',
                        help='Launch with IDLE shell')
    group.add_argument('-w', '--pyw', action='store_true', dest='pyw',
                        help='Launch without CMD console')
    parser.add_argument('script', nargs='*',
                        help='Script to launch')
    if len(sys.argv) < 2: args = parser.parse_args(['-h'])
    else: args = parser.parse_args()

    # Get and save new install paths 
    if args.setup or not os.path.exists(os.path.join(data_dir, cfg_file)):
        for ver in (('2.x', '26'), ('3.x', '32')):
            while True:
                install_path = input('Enter path for Python {0} [C:\\Python{1}]: '.format(*ver)).rstrip('\r') #rstrip until bug fixed: http://bugs.python.org/issue11272
                if install_path == 'q': sys.exit(0)
                if install_path == '': install_path = 'C:\\Python{0}'.format(ver[1])
                if os.path.exists(os.path.join(install_path, 'python.exe')):
                    py_ver[ver[0][0]] = install_path
                    print()
                    break
                else: print('Python executable not found in that path. Try again or (q)uit.\n')
        _saveR(cfg_file, py_ver)

    # Load install paths from last time
    if not py_ver:
        py_ver = _loadR(cfg_file)

# Script and additional argument processing
    add_args = args.script
    script = add_args.pop(0)

    # Require script with certain switches
    if not script:
        if args.idle or args.pyw:
            print('Script argument required with this switch. Use -h for help.')

    # Launch script if provided
    else:
        if os.path.exists(script):
            with open(script, mode='r', encoding='utf-8') as f:
                hashbang = f.readline()

            py_num = str(int('python2' not in hashbang) + 2) #translate 2 or 3 version num  
            py_path = py_ver[py_num]

            if args.pyw:
                cmd_line = '''start "" "{}\\pythonw.exe" "{}" {}'''.format(py_path, script, ' '.join(add_args))

            elif args.idle:
                cmd_line = '''start "" "{0}\\pythonw.exe" "{0}\\Lib\\idlelib\\idle.pyw" -e "{1}"'''.format(py_path, script)

            else:
                cmd_line = '''cmd /K ""{}\\python.exe" "{}" {}"'''.format(py_path, script, ' '.join(add_args))

            os.system(cmd_line)

        else: print('Script not found ({0})'.format(script))
Beispiel #38
0
data_files = data_files_config('config','openzwave/config','*.xml')
data_files.extend(data_files_config('config','openzwave/config','*.xsd'))

cmdclass = { }
ext_modules = [ ]

if os_name == 'win32':
    ext_modules = [Extension("libopenzwave",
                             sources=["src-lib/libopenzwave/libopenzwave.pyx"],
                             libraries=['setupapi', 'stdc++'],
                             language="c++",
                             extra_objects=['openzwave/libopenzwave.a'],
                             include_dirs=['openzwave/cpp/src', 'openzwave/cpp/src/value_classes', 'openzwave/cpp/src/platform', 'openzwave/cpp/build/windows', "src-lib/libopenzwave"]
    )]
elif platform_system() == 'darwin':
    ext_modules = [Extension("libopenzwave",
                             sources=["src-lib/libopenzwave/libopenzwave.pyx"],
                             libraries=['udev', 'stdc++'],
                             language="c++",
                             extra_link_args=['-framework', 'CoreFoundation', '-framework', 'IOKit'],
                             extra_objects=['openzwave/libopenzwave.a'],
                             include_dirs=['openzwave/cpp/src', 'openzwave/cpp/src/value_classes', 'openzwave/cpp/src/platform', 'openzwave/cpp/build/mac', "src-lib/libopenzwave"]
    )]
elif DEBIAN_PACKAGE == True:
    ext_modules = [Extension("libopenzwave",
                             sources=["src-lib/libopenzwave/libopenzwave.pyx"],
                             libraries=['udev', 'stdc++', 'openzwave'],
                             language="c++",
                             #extra_objects=['/usr/libopenzwave.a'],
                             include_dirs=['/usr/include/openzwave', '/usr/include/openzwave/value_classes', '/usr/include/openzwave/platform', "src-lib/libopenzwave"]
Beispiel #39
0
    def _gettrainingdata(self):
        files = [path.join(w_path, filename)
                 for w_path, dirs, files in walk(self.settings['data_dir'] + "/" + 'raw')
                 for filename in files
                 if not filename.endswith(".csv")]
        while 1:
            rfile = random_choice(files)

            trash  = len(listdir(self.settings['data_dir'] + "/" + 'training/trash'))
            plain  = len(listdir(self.settings['data_dir'] + "/" + 'training/plain'))
            hashes = len(listdir(self.settings['data_dir'] + "/" + 'training/hash'))

            # Clear the screen before displaying the text
            system('cls' if name == 'nt' else 'clear')

            # Let's the terminal size, so I can fill it with the file text
            cols, rows = get_terminal_size()

            print colorama.Fore.YELLOW + rfile
            print("")

            with open(rfile) as tfile:
                i = 0
                for line in tfile:
                    i += 1
                    if i >= (rows - 6):
                        break

                    if len(line) <= cols:
                        print line.strip('\n\r')
                    else:
                        print line[0:cols].strip('\n\r')

            print("")
            print colorama.Fore.YELLOW + "Trash: " + str(trash) + " Plain: " + str(plain) + " Hash: " + str(hashes)

            input_descr = colorama.Fore.MAGENTA + "[o]"
            input_descr += colorama.Fore.CYAN + "open "
            input_descr += colorama.Fore.MAGENTA + "[t]"
            input_descr += colorama.Fore.CYAN + "rash "
            input_descr += colorama.Fore.MAGENTA + "[p]"
            input_descr += colorama.Fore.CYAN + "lain "
            input_descr += colorama.Fore.MAGENTA + "[h]"
            input_descr += colorama.Fore.CYAN + "ash "
            input_descr += colorama.Fore.MAGENTA + "[s]"
            input_descr += colorama.Fore.CYAN + "kip "
            input_descr += colorama.Fore.MAGENTA + "[q]"
            input_descr += colorama.Fore.CYAN + "uit=> "

            sys_stdout.write(input_descr)
            sys_stdout.flush()

            answer = getch()

            while answer == '':
                pass

            # Opening a file with the default application AND being cross platform is a PITA...
            if answer == 'o':
                current_os = platform_system()
                if current_os == 'Windows':
                    from os import startfile as os_startfile
                    os_startfile(rfile)
                elif current_os == 'Linux':
                    subprocess_call(["xdg-open", rfile])
                elif current_os == 'Darwin':
                    system("open " + rfile)

                # Let's start the loop again to read the new key
                answer = getch()

                while answer == '':
                    pass

            if answer == 't':
                shutil_copyfile(rfile, self.settings['data_dir'] + "/" + 'training/trash/' + path.basename(rfile))
            elif answer == 'p':
                shutil_copyfile(rfile, self.settings['data_dir'] + "/" + 'training/plain/' + path.basename(rfile))
            elif answer == 'h':
                shutil_copyfile(rfile, self.settings['data_dir'] + "/" + 'training/hash/' + path.basename(rfile))
            elif answer == 's':
                print("")
                continue
            elif answer == 'q':
                print("")
                print(colorama.Fore.GREEN + "Training complete")
                break
            else:
                print("")
                continue
Beispiel #40
0
install_gobject_iteration()

from math import floor
from types import *
from xmmscon import XmmsConnection, SeekException

import gobject
from platform import system as platform_system

# def gen_cb(value):
#     print "gen_cb: ", value
# 

from kivy.uix.widget import Widget

if platform_system() == "Darwin":
    #running on mac so use mac control...
    from osax import *
    def _set_sys_volume():
        


class VolumeWidget(Widget):
    def __init__(self, **kwargs):
        super(VolumeWidget, self).__init__(**kwargs)
        
    
        

class MediaBar2(Widget):
    
Beispiel #41
0
    def run(self):
        stop = False

        for folder in ['trash', 'plain', 'hash']:
            if stop:
                break

            # Let's convert the single date to a path
            arg_dir = '/'.join(self.parentArgs.dir.split('-'))
            review_folder = self.settings['data_dir'] + '/organized/' + folder + "/" + arg_dir

            if not os_path.exists(review_folder):
                print 'Folder "' + folder + '" not found, skipping...'
                continue

            files = [os_path.join(w_path, filename)
                     for w_path, dirs, files in os_walk(review_folder)
                     for filename in files
                     if not filename.endswith(".csv")]

            idx = 0

            while idx < len(files):
                rfile = files[idx]

                # Clear the screen before displaying the text
                system('cls' if name == 'nt' else 'clear')

                # Let's the terminal size, so I can fill it with the file text
                cols, rows = get_terminal_size()

                print colorama.Fore.YELLOW + rfile
                print("")

                with open(rfile) as tfile:
                    i = 0
                    for line in tfile:
                        i += 1
                        if i >= (rows - 6):
                            break

                        if len(line) <= cols:
                            print line.strip('\n\r')
                        else:
                            print line[0:cols].strip('\n\r')

                files_left = len(files) - idx
                print("")
                print colorama.Fore.YELLOW + "Folder: " + folder + " " + colorama.Fore.CYAN + str(files_left) + colorama.Fore.YELLOW + " files left"

                input_descr = colorama.Fore.MAGENTA + "[o]"
                input_descr += colorama.Fore.CYAN + "open "
                input_descr += colorama.Fore.MAGENTA + "[s]"
                input_descr += colorama.Fore.CYAN + "kip folder "
                input_descr += colorama.Fore.MAGENTA + "[n]"
                input_descr += colorama.Fore.CYAN + "ext "
                input_descr += colorama.Fore.MAGENTA + "[p]"
                input_descr += colorama.Fore.CYAN + "revious "
                input_descr += colorama.Fore.MAGENTA + "[q]"
                input_descr += colorama.Fore.CYAN + "uit=> "

                sys_stdout.write(input_descr)
                sys_stdout.flush()

                answer = getch()

                while answer == '':
                    pass

                idx += 1

                # Opening a file with the default application AND being cross platform is a PITA...
                if answer == 'o':
                    current_os = platform_system()
                    if current_os == 'Windows':
                        from os import startfile as os_startfile
                        os_startfile(rfile)
                    elif current_os == 'Linux':
                        subprocess_call(["xdg-open", rfile])
                    elif current_os == 'Darwin':
                        system("open " + rfile)

                    # Let's start the loop again to read the new key
                    answer = getch()

                    while answer == '':
                        pass

                if answer == 'n':
                    print("")
                elif answer == 'p':
                    if idx >= 2:
                        idx -= 2
                    continue
                elif answer == 's':
                    break
                elif answer == 'q':
                    print("")
                    stop = True
                    break
                else:
                    print("")

        print(colorama.Fore.GREEN + "Review completed")
Beispiel #42
0
    ret.append(tup)
    dirs = _getDirs(source)
    if len(dirs):
        for d in dirs:
            rd = d.replace(source+os.sep, "", 1)
            ret.extend(data_files_config(os.path.join(target,rd), \
                os.path.join(source,rd), pattern))
    return ret

data_files = data_files_config('config','openzwave/config','*.xml')
data_files.extend(data_files_config('config','openzwave/config','*.xsd'))

cmdclass = { }
ext_modules = [ ]

if platform_system() == 'Windows':
    ext_modules = [Extension("libopenzwave",
                             sources=["src-lib/libopenzwave/libopenzwave.pyx"],
                             libraries=['setupapi', 'stdc++'],
                             language="c++",
                             extra_objects=['openzwave/libopenzwave.a'],
                             include_dirs=['openzwave/cpp/src', 'openzwave/cpp/src/value_classes', 'openzwave/cpp/src/platform', 'openzwave/cpp/build/windows', "src-lib/libopenzwave"]
    )]
elif platform_system() == 'Darwin':
    ext_modules = [Extension("libopenzwave",
                             sources=["src-lib/libopenzwave/libopenzwave.pyx"],
                             libraries=['stdc++'],
                             language="c++",
                             extra_link_args=['-framework', 'CoreFoundation', '-framework', 'IOKit'],
                             extra_objects=['openzwave/libopenzwave.a'],
                             include_dirs=['openzwave/cpp/src', 'openzwave/cpp/src/value_classes', 'openzwave/cpp/src/platform', 'openzwave/cpp/build/mac', "src-lib/libopenzwave"]
Beispiel #43
0
data_files = data_files_config('config','openzwave/config','*.xml')
data_files.extend(data_files_config('config','openzwave/config','*.xsd'))

cmdclass = { }
ext_modules = [ ]

if os_name == 'win32' or os_name=='nt':
    ext_modules = [Extension("libopenzwave",
                             sources=["src-lib/libopenzwave/libopenzwave.pyx"],
                             libraries=['setupapi', 'stdc++'],
                             language="c++",
                             extra_objects=['openzwave/libopenzwave.a'],
                             include_dirs=['openzwave/cpp/src', 'openzwave/cpp/src/value_classes', 'openzwave/cpp/src/platform', 'openzwave/cpp/build/windows', "src-lib/libopenzwave"]
    )]
elif platform_system() == 'darwin':
    ext_modules = [Extension("libopenzwave",
                             sources=["src-lib/libopenzwave/libopenzwave.pyx"],
                             libraries=['udev', 'stdc++'],
                             language="c++",
                             extra_link_args=['-framework', 'CoreFoundation', '-framework', 'IOKit'],
                             extra_objects=['openzwave/libopenzwave.a'],
                             include_dirs=['openzwave/cpp/src', 'openzwave/cpp/src/value_classes', 'openzwave/cpp/src/platform', 'openzwave/cpp/build/mac', "src-lib/libopenzwave"]
    )]
elif DEBIAN_PACKAGE == True:
    ext_modules = [Extension("libopenzwave",
                             sources=["src-lib/libopenzwave/libopenzwave.pyx"],
                             libraries=['udev', 'stdc++', 'openzwave'],
                             language="c++",
                             define_macros=[ 
                                 ('PY_SSIZE_T_CLEAN',1),