当前位置: 首页>>代码示例>>Python>>正文


Python TimedOperation.run方法代码示例

本文整理汇总了Python中timedops.TimedOperation.run方法的典型用法代码示例。如果您正苦于以下问题:Python TimedOperation.run方法的具体用法?Python TimedOperation.run怎么用?Python TimedOperation.run使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在timedops.TimedOperation的用法示例。


在下文中一共展示了TimedOperation.run方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: NetworkCUPSPrinterShared

# 需要导入模块: from timedops import TimedOperation [as 别名]
# 或者: from timedops.TimedOperation import run [as 别名]
class NetworkCUPSPrinterShared(Question):
    def __init__ (self, troubleshooter):
        Question.__init__ (self, troubleshooter, "Queue not shared?")
        page = self.initial_vbox (_("Queue Not Shared"),
                                  _("The CUPS printer on the server is not "
                                    "shared."))
        troubleshooter.new_page (page, self)

    def display (self):
        self.answers = {}
        answers = self.troubleshooter.answers
        if ('remote_cups_queue_listed' in answers and
            answers['remote_cups_queue_listed'] == False):
            return False

        parent = self.troubleshooter.get_window ()
        if 'remote_cups_queue_attributes' not in answers:
            if not ('remote_server_try_connect' in answers and
                    'remote_cups_queue' in answers):
                return False

            try:
                host = answers['remote_server_try_connect']
                self.op = TimedOperation (cups.Connection,
                                          kwargs={"host": host},
                                          parent=parent)
                c = self.op.run ()
                self.op = TimedOperation (c.getPrinterAttributes,
                                          args=(answers['remote_cups_queue'],),
                                          parent=parent)
                attr = self.op.run ()
            except RuntimeError:
                return False
            except cups.IPPError:
                return False

            self.answers['remote_cups_queue_attributes'] = attr
        else:
            attr = answers['remote_cups_queue_attributes']

        if 'printer-is-shared' in attr:
            # CUPS >= 1.2
            if not attr['printer-is-shared']:
                return True

        return False

    def can_click_forward (self):
        return False

    def collect_answer (self):
        return self.answers

    def cancel_operation (self):
        self.op.cancel ()
开发者ID:Distrotech,项目名称:system-config-printer,代码行数:57,代码来源:NetworkCUPSPrinterShared.py

示例2: Welcome

# 需要导入模块: from timedops import TimedOperation [as 别名]
# 或者: from timedops.TimedOperation import run [as 别名]
class Welcome(Question):
    def __init__ (self, troubleshooter):
        Question.__init__ (self, troubleshooter, "Welcome")
        welcome = gtk.HBox ()
        welcome.set_spacing (12)
        welcome.set_border_width (12)
        image = gtk.Image ()
        image.set_alignment (0, 0)
        image.set_from_stock (gtk.STOCK_PRINT, gtk.ICON_SIZE_DIALOG)
        intro = gtk.Label ('<span weight="bold" size="larger">' +
                           _("Trouble-shooting Printing") +
                           '</span>\n\n' +
                           _("The next few screens will contain some "
                             "questions about your problem with printing. "
                             "Based on your answers a solution may be "
                             "suggested.") + '\n\n' +
                           _("Click 'Forward' to begin."))
        intro.set_alignment (0, 0)
        intro.set_use_markup (True)
        intro.set_line_wrap (True)
        welcome.pack_start (image, False, False, 0)
        welcome.pack_start (intro, True, True, 0)
        page = troubleshooter.new_page (welcome, self)

    def collect_answer (self):
        parent = self.troubleshooter.get_window ()
        # Store the authentication dialog instance in the answers.  This
        # allows the password to be cached.
        factory = AuthConnFactory (parent)
        self.op = TimedOperation (factory.get_connection, parent=parent)
        return {'_authenticated_connection_factory': factory,
                '_authenticated_connection': self.op.run () }

    def cancel_operation (self):
        self.op.cancel ()
开发者ID:Alberto-Beralix,项目名称:Beralix,代码行数:37,代码来源:Welcome.py

示例3: SchedulerNotRunning

# 需要导入模块: from timedops import TimedOperation [as 别名]
# 或者: from timedops.TimedOperation import run [as 别名]
class SchedulerNotRunning(Question):
    def __init__ (self, troubleshooter):
        Question.__init__ (self, troubleshooter, "Scheduler not running?")
        page = self.initial_vbox (_("CUPS Service Stopped"),
                                  _("The CUPS print spooler does not appear "
                                    "to be running.  To correct this, choose "
                                    "System->Administration->Services from "
                                    "the main menu and look for the 'cups' "
                                    "service."))
        troubleshooter.new_page (page, self)

    def display (self):
        self.answers = {}
        if self.troubleshooter.answers.get ('cups_queue_listed', False):
            return False

        parent = self.troubleshooter.get_window ()

        # Find out if CUPS is running.
        failure = False
        try:
            self.op = TimedOperation (cups.Connection,
                                      parent=parent)
            c = self.op.run ()
        except RuntimeError:
            failure = True

        self.answers['cups_connection_failure'] = failure
        return failure

    def can_click_forward (self):
        return False

    def collect_answer (self):
        return self.answers

    def cancel_operation (self):
        self.op.cancel ()
开发者ID:Distrotech,项目名称:system-config-printer,代码行数:40,代码来源:SchedulerNotRunning.py

示例4: ErrorLogFetch

# 需要导入模块: from timedops import TimedOperation [as 别名]
# 或者: from timedops.TimedOperation import run [as 别名]
class ErrorLogFetch(Question):
    def __init__ (self, troubleshooter):
        Question.__init__ (self, troubleshooter, "Error log fetch")
        troubleshooter.new_page (gtk.Label (), self)
        self.persistent_answers = {}

    def display (self):
        answers = self.troubleshooter.answers
        parent = self.troubleshooter.get_window ()
        self.answers = {}
        try:
            checkpoint = answers['error_log_checkpoint']
        except KeyError:
            checkpoint = None

        if self.persistent_answers.has_key ('error_log'):
            checkpoint = None

        def fetch_log (c):
            prompt = c._get_prompt_allowed ()
            c._set_prompt_allowed (False)
            c._connect ()
            (tmpfd, tmpfname) = tempfile.mkstemp ()
            os.close (tmpfd)
            success = False
            try:
                c.getFile ('/admin/log/error_log', tmpfname)
                success = True
            except cups.HTTPError:
                try:
                    os.remove (tmpfname)
                except OSError:
                    pass

            c._set_prompt_allowed (prompt)
            if success:
                return tmpfname
            return None

        self.authconn = self.troubleshooter.answers['_authenticated_connection']
        if answers.has_key ('error_log_debug_logging_set'):
            try:
                self.op = TimedOperation (self.authconn.adminGetServerSettings,
                                          parent=parent)
                settings = self.op.run ()
            except cups.IPPError:
                return False

            settings[cups.CUPS_SERVER_DEBUG_LOGGING] = '0'
            orig_settings = answers['cups_server_settings']
            settings['MaxLogSize'] = orig_settings.get ('MaxLogSize', '2000000')
            success = False
            def set_settings (connection, settings):
                connection.adminSetServerSettings (settings)

                # Now reconnect.
                attempt = 1
                while attempt <= 5:
                    try:
                        time.sleep (1)
                        connection._connect ()
                        break
                    except RuntimeError:
                        # Connection failed
                        attempt += 1

            try:

                self.op = TimedOperation (set_settings,
                                          (self.authconn, settings),
                                          parent=parent)
                self.op.run ()
                self.persistent_answers['error_log_debug_logging_unset'] = True
            except cups.IPPError:
                pass

        if checkpoint != None:
            self.op = TimedOperation (fetch_log,
                                      (self.authconn,),
                                      parent=parent)
            tmpfname = self.op.run ()
            if tmpfname != None:
                f = file (tmpfname)
                f.seek (checkpoint)
                lines = f.readlines ()
                os.remove (tmpfname)
                self.answers = { 'error_log': map (lambda x: x.strip (),
                                                   lines) }

        return False

    def collect_answer (self):
        answers = self.persistent_answers.copy ()
        answers.update (self.answers)
        return answers

    def cancel_operation (self):
        self.op.cancel ()

        # Abandon the CUPS connection and make another.
#.........这里部分代码省略.........
开发者ID:Alberto-Beralix,项目名称:Beralix,代码行数:103,代码来源:ErrorLogFetch.py

示例5: ErrorLogCheckpoint

# 需要导入模块: from timedops import TimedOperation [as 别名]
# 或者: from timedops.TimedOperation import run [as 别名]
class ErrorLogCheckpoint(Question):
    def __init__ (self, troubleshooter):
        Question.__init__ (self, troubleshooter, "Error log checkpoint")
        page = self.initial_vbox (_("Debugging"),
                                  _("This step will enable debugging output "
                                    "from the CUPS scheduler.  This may "
                                    "cause the scheduler to restart.  Click "
                                    "the button below to enable debugging."))
        button = gtk.Button (_("Enable Debugging"))
        buttonbox = gtk.HButtonBox ()
        buttonbox.set_border_width (0)
        buttonbox.set_layout (gtk.BUTTONBOX_START)
        buttonbox.pack_start (button, False, False, 0)
        self.button = button
        page.pack_start (buttonbox, False, False, 0)
        self.label = gtk.Label ()
        self.label.set_alignment (0, 0)
        self.label.set_line_wrap (True)
        page.pack_start (self.label, False, False, 0)
        troubleshooter.new_page (page, self)
        self.persistent_answers = {}

    def __del__ (self):
        if not self.persistent_answers.get ('error_log_debug_logging_set',
                                            False):
            return

        c = self.troubleshooter.answers['_authenticated_connection']
        c._set_lock (False)
        settings = c.adminGetServerSettings ()
        if len (settings.keys ()) == 0:
            return

        settings[cups.CUPS_SERVER_DEBUG_LOGGING] = '0'
        answers = self.troubleshooter.answers
        orig_settings = self.persistent_answers['cups_server_settings']
        settings['MaxLogSize'] = orig_settings.get ('MaxLogSize', '2000000')
        c.adminSetServerSettings (settings)

    def display (self):
        self.answers = {}
        answers = self.troubleshooter.answers
        if not answers['cups_queue_listed']:
            return False

        self.authconn = answers['_authenticated_connection']
        parent = self.troubleshooter.get_window ()

        def getServerSettings ():
            # Fail if auth required.
            cups.setPasswordCB (lambda x: '')
            cups.setServer ('')
            c = cups.Connection ()
            return c.adminGetServerSettings ()

        try:
            self.op = TimedOperation (getServerSettings, parent=parent)
            settings = self.op.run ()
        except RuntimeError:
            return False
        except cups.IPPError:
            settings = {}

        self.forward_allowed = False
        self.label.set_text ('')
        if len (settings.keys ()) == 0:
            # Requires root
            return True
        else:
            self.persistent_answers['cups_server_settings'] = settings

        try:
            if int (settings[cups.CUPS_SERVER_DEBUG_LOGGING]) != 0:
                # Already enabled
                return False
        except KeyError:
            pass
        except ValueError:
            pass

        return True

    def connect_signals (self, handler):
        self.button_sigid = self.button.connect ('clicked', self.enable_clicked,
                                                 handler)

    def disconnect_signals (self):
        self.button.disconnect (self.button_sigid)

    def collect_answer (self):
        answers = self.troubleshooter.answers
        if not answers['cups_queue_listed']:
            return {}

        parent = self.troubleshooter.get_window ()
        self.answers.update (self.persistent_answers)
        if self.answers.has_key ('error_log_checkpoint'):
            return self.answers

        (tmpfd, tmpfname) = tempfile.mkstemp ()
#.........这里部分代码省略.........
开发者ID:Alberto-Beralix,项目名称:Beralix,代码行数:103,代码来源:ErrorLogCheckpoint.py

示例6: ErrorLogFetch

# 需要导入模块: from timedops import TimedOperation [as 别名]
# 或者: from timedops.TimedOperation import run [as 别名]
class ErrorLogFetch(Question):
    def __init__ (self, troubleshooter):
        Question.__init__ (self, troubleshooter, "Error log fetch")
        page = self.initial_vbox (_("Retrieve Journal Entries"),
                                  _("No system journal entries were found. "
                                    "This may be because you are not an "
                                    "administrator. To fetch journal entries "
                                    "please run this command:"))
        self.entry = Gtk.Entry ()
        self.entry.set_editable (False)
        page.pack_start (self.entry, False, False, 0)
        troubleshooter.new_page (page, self)
        self.persistent_answers = {}

    def display (self):
        answers = self.troubleshooter.answers
        parent = self.troubleshooter.get_window ()
        self.answers = {}
        checkpoint = answers.get ('error_log_checkpoint')
        cursor = answers.get ('error_log_cursor')
        timestamp = answers.get ('error_log_timestamp')

        if ('error_log' in self.persistent_answers or
            'journal' in self.persistent_answers):
            checkpoint = None
            cursor = None

        def fetch_log (c):
            prompt = c._get_prompt_allowed ()
            c._set_prompt_allowed (False)
            c._connect ()
            with tempfile.NamedTemporaryFile (delete=False) as tmpf:
                success = False
                try:
                    c.getFile ('/admin/log/error_log', tmpf.file)
                    success = True
                except cups.HTTPError:
                    try:
                        os.remove (tmpf.file)
                    except OSError:
                        pass

                c._set_prompt_allowed (prompt)
                if success:
                    return tmpf.file

            return None

        now = datetime.datetime.fromtimestamp (time.time ()).strftime ("%F %T")
        self.authconn = self.troubleshooter.answers['_authenticated_connection']
        if 'error_log_debug_logging_set' in answers:
            try:
                self.op = TimedOperation (self.authconn.adminGetServerSettings,
                                          parent=parent)
                settings = self.op.run ()
            except cups.IPPError:
                return False

            settings[cups.CUPS_SERVER_DEBUG_LOGGING] = '0'
            orig_settings = answers['cups_server_settings']
            settings['MaxLogSize'] = orig_settings.get ('MaxLogSize', '2000000')
            success = False
            def set_settings (connection, settings):
                connection.adminSetServerSettings (settings)

                # Now reconnect.
                attempt = 1
                while attempt <= 5:
                    try:
                        time.sleep (1)
                        connection._connect ()
                        break
                    except RuntimeError:
                        # Connection failed
                        attempt += 1

            try:

                self.op = TimedOperation (set_settings,
                                          (self.authconn, settings),
                                          parent=parent)
                self.op.run ()
                self.persistent_answers['error_log_debug_logging_unset'] = True
            except cups.IPPError:
                pass

        self.answers = {}
        if journal and cursor != None:
            def journal_format (x):
                try:
                    priority = "XACEWNIDd"[x['PRIORITY']]
                except (IndexError, TypeError):
                    priority = " "

                return (priority + " " +
                        x['__REALTIME_TIMESTAMP'].strftime("[%m/%b/%Y:%T]") +
                        " " + x['MESSAGE'])

            r = journal.Reader ()
            r.seek_cursor (cursor)
#.........这里部分代码省略.........
开发者ID:Distrotech,项目名称:system-config-printer,代码行数:103,代码来源:ErrorLogFetch.py

示例7: ErrorLogFetch

# 需要导入模块: from timedops import TimedOperation [as 别名]
# 或者: from timedops.TimedOperation import run [as 别名]
class ErrorLogFetch(Question):
    def __init__ (self, troubleshooter):
        Question.__init__ (self, troubleshooter, "Error log fetch")
        troubleshooter.new_page (Gtk.Label (), self)
        self.persistent_answers = {}

    def display (self):
        answers = self.troubleshooter.answers
        parent = self.troubleshooter.get_window ()
        self.answers = {}
        checkpoint = answers.get ('error_log_checkpoint')
        cursor = answers.get ('error_log_cursor')

        if ('error_log' in self.persistent_answers or
            'journal' in self.persistent_answers):
            checkpoint = None
            cursor = None

        def fetch_log (c):
            prompt = c._get_prompt_allowed ()
            c._set_prompt_allowed (False)
            c._connect ()
            (tmpfd, tmpfname) = tempfile.mkstemp ()
            os.close (tmpfd)
            success = False
            try:
                c.getFile ('/admin/log/error_log', tmpfname)
                success = True
            except cups.HTTPError:
                try:
                    os.remove (tmpfname)
                except OSError:
                    pass

            c._set_prompt_allowed (prompt)
            if success:
                return tmpfname
            return None

        self.authconn = self.troubleshooter.answers['_authenticated_connection']
        if 'error_log_debug_logging_set' in answers:
            try:
                self.op = TimedOperation (self.authconn.adminGetServerSettings,
                                          parent=parent)
                settings = self.op.run ()
            except cups.IPPError:
                return False

            settings[cups.CUPS_SERVER_DEBUG_LOGGING] = '0'
            orig_settings = answers['cups_server_settings']
            settings['MaxLogSize'] = orig_settings.get ('MaxLogSize', '2000000')
            success = False
            def set_settings (connection, settings):
                connection.adminSetServerSettings (settings)

                # Now reconnect.
                attempt = 1
                while attempt <= 5:
                    try:
                        time.sleep (1)
                        connection._connect ()
                        break
                    except RuntimeError:
                        # Connection failed
                        attempt += 1

            try:

                self.op = TimedOperation (set_settings,
                                          (self.authconn, settings),
                                          parent=parent)
                self.op.run ()
                self.persistent_answers['error_log_debug_logging_unset'] = True
            except cups.IPPError:
                pass

        self.answers = {}
        if journal and cursor != None:
            def journal_format (x):
                try:
                    priority = "XACEWNIDd"[x['PRIORITY']]
                except (IndexError, TypeError):
                    priority = " "

                return (priority + " " +
                        x['__REALTIME_TIMESTAMP'].strftime("[%m/%b/%Y:%T]") +
                        " " + x['MESSAGE'])

            r = journal.Reader ()
            r.seek_cursor (cursor)
            r.add_match (_COMM="cupsd")
            self.answers['journal'] = [journal_format (x) for x in r]

        if checkpoint != None:
            self.op = TimedOperation (fetch_log,
                                      (self.authconn,),
                                      parent=parent)
            tmpfname = self.op.run ()
            if tmpfname != None:
                f = open (tmpfname)
#.........这里部分代码省略.........
开发者ID:daniel-dressler,项目名称:system-config-printer,代码行数:103,代码来源:ErrorLogFetch.py

示例8: PrintTestPage

# 需要导入模块: from timedops import TimedOperation [as 别名]
# 或者: from timedops.TimedOperation import run [as 别名]

#.........这里部分代码省略.........
        self.main_label.set_markup (label_text)

        model = Gtk.ListStore (bool,
                               int,
                               str,
                               str,
                               str)
        self.treeview.set_model (model)
        self.job_to_iter = {}

        test_jobs = self.persistent_answers.get ('test_page_job_id', [])
        def get_jobs ():
            c = self.authconn
            try:
                r = ["job-id",
                     "job-name",
                     "job-state",
                     "job-printer-uri",
                     "printer-name"]
                jobs_dict = c.getJobs (which_jobs='not-completed',
                                       my_jobs=False,
                                       requested_attributes=r)
                completed_jobs_dict = c.getJobs (which_jobs='completed',
                                                 requested_attributes=r)
            except TypeError:
                # requested_attributes requires pycups 1.9.50
                jobs_dict = c.getJobs (which_jobs='not-completed',
                                       my_jobs=False)
                completed_jobs_dict = c.getJobs (which_jobs='completed')
            return (jobs_dict, completed_jobs_dict)

        self.op = TimedOperation (get_jobs, parent=parent)
        try:
            (jobs_dict, completed_jobs_dict) = self.op.run ()
        except (OperationCanceled, cups.IPPError):
            return False

        # We want to display the jobs in the queue for this printer...
        try:
            queue_uri_ending = "/" + self.troubleshooter.answers['cups_queue']
            jobs_on_this_printer = [x for x in jobs_dict.keys () if \
                                            jobs_dict[x]['job-printer-uri']. \
                                            endswith (queue_uri_ending)]
        except:
            jobs_on_this_printer = []

        # ...as well as any other jobs we've previous submitted as test pages.
        jobs = list (set(test_jobs).union (set (jobs_on_this_printer)))

        completed_jobs_dict = None
        for job in jobs:
            try:
                j = jobs_dict[job]
            except KeyError:
                try:
                    j = completed_jobs_dict[job]
                except KeyError:
                    continue

            iter = model.append (None)
            self.job_to_iter[job] = iter
            model.set_value (iter, 0, job in test_jobs)
            model.set_value (iter, 1, job)
            self.update_job (job, j)

        return True
开发者ID:Distrotech,项目名称:system-config-printer,代码行数:70,代码来源:PrintTestPage.py

示例9: ChooseNetworkPrinter

# 需要导入模块: from timedops import TimedOperation [as 别名]
# 或者: from timedops.TimedOperation import run [as 别名]
class ChooseNetworkPrinter(Question):
    def __init__ (self, troubleshooter):
        Question.__init__ (self, troubleshooter, "Choose network printer")
        page1 = self.initial_vbox (_("Choose Network Printer"),
                                   _("Please select the network printer you "
                                     "are trying to use from the list below. "
                                     "If it does not appear in the list, "
                                     "select 'Not listed'."))
        tv = Gtk.TreeView ()
        name = Gtk.TreeViewColumn (_("Name"),
                                   Gtk.CellRendererText (), text=0)
        location = Gtk.TreeViewColumn (_("Location"),
                                       Gtk.CellRendererText (), text=1)
        info = Gtk.TreeViewColumn (_("Information"),
                                   Gtk.CellRendererText (), text=2)
        name.set_property ("resizable", True)
        location.set_property ("resizable", True)
        info.set_property ("resizable", True)
        tv.append_column (name)
        tv.append_column (location)
        tv.append_column (info)
        tv.set_rules_hint (True)
        sw = Gtk.ScrolledWindow ()
        sw.set_policy (Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
        sw.set_shadow_type (Gtk.ShadowType.IN)
        sw.add (tv)
        page1.pack_start (sw, True, True, 0)
        self.treeview = tv
        troubleshooter.new_page (page1, self)

    def display (self):
        answers = self.troubleshooter.answers
        if answers['cups_queue_listed']:
            return False

        if not answers.get ('remote_server_cups', False):
            return False

        server = answers['remote_server_try_connect']

        model = Gtk.ListStore (str,
                               str,
                               str,
                               GObject.TYPE_PYOBJECT)
        self.model = model
        self.treeview.set_model (model)
        iter = model.append (None)
        model.set (iter, 0, _("Not listed"), 1, '', 2, '', 3, 0)

        parent = self.troubleshooter.get_window ()

        try:
            self.op = TimedOperation (cups.Connection, 
                                      kwargs={"host": server},
                                      parent=parent)
            c = self.op.run ()
            self.op = TimedOperation (c.getDests, parent=parent)
            dests = self.op.run ()
            printers = None
            dests_list = []
            for (name, instance), dest in dests.items ():
                if name is None:
                    continue

                if instance is not None:
                    queue = "%s/%s" % (name, instance)
                else:
                    queue = name

                if printers is None:
                    self.op = TimedOperation (c.getPrinters)
                    printers = self.op.run ()

                if name not in printers:
                    info = _("Unknown")
                    location = _("Unknown")
                else:
                    printer = printers[name]
                    info = printer.get('printer-info', _("Unknown"))
                    location = printer.get('printer-location', _("Unknown"))

                dests_list.append ((queue, location, info, dest))

            dests_list.sort (key=lambda x: x[0])
            for queue, location, info, dest in dests_list:
                iter = model.append (None)
                model.set (iter, 0, queue, 1, location, 2, info, 3, dest)

        except cups.HTTPError:
            pass
        except cups.IPPError:
            pass
        except RuntimeError:
            pass

        return True

    def connect_signals (self, handler):
        self.signal_id = self.treeview.connect ("cursor-changed", handler)

#.........这里部分代码省略.........
开发者ID:antlarr,项目名称:system-config-printer,代码行数:103,代码来源:ChooseNetworkPrinter.py

示例10: DeviceListed

# 需要导入模块: from timedops import TimedOperation [as 别名]
# 或者: from timedops.TimedOperation import run [as 别名]
class DeviceListed(Question):
    def __init__ (self, troubleshooter):
        # Is the device listed?
        Question.__init__ (self, troubleshooter, "Choose device")
        page1 = self.initial_vbox (_("Choose Device"),
                                   _("Please select the device you want "
                                     "to use from the list below. "
                                     "If it does not appear in the list, "
                                     "select 'Not listed'."))
        tv = Gtk.TreeView ()
        name = Gtk.TreeViewColumn (_("Name"),
                                   Gtk.CellRendererText (), text=0)
        info = Gtk.TreeViewColumn (_("Information"),
                                   Gtk.CellRendererText (), text=1)
        uri = Gtk.TreeViewColumn (_("Device URI"),
                                  Gtk.CellRendererText (), text=2)
        name.set_property ("resizable", True)
        info.set_property ("resizable", True)
        uri.set_property ("resizable", True)
        tv.append_column (name)
        tv.append_column (info)
        tv.append_column (uri)
        tv.set_rules_hint (True)
        sw = Gtk.ScrolledWindow ()
        sw.set_policy (Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC)
        sw.set_shadow_type (Gtk.ShadowType.IN)
        sw.add (tv)
        page1.pack_start (sw, True, True, 0)
        self.treeview = tv
        troubleshooter.new_page (page1, self)

    def display (self):
        self.answers = {}
        answers = self.troubleshooter.answers
        if (answers['printer_is_remote'] or
            answers.get ('cups_printer_remote', False)):
            return False

        model = Gtk.ListStore (str,
                               str,
                               str,
                               GObject.TYPE_PYOBJECT)
        self.treeview.set_model (model)
        iter = model.append (None)
        model.set (iter, 0, _("Not listed"), 1, '', 2, '', 3, NotListed)

        devices = {}
        parent = self.troubleshooter.get_window ()
        # Skip device list if this page is hidden and we're skipping
        # backwards past it.
        if not (answers['cups_queue_listed'] and
                self.troubleshooter.is_moving_backwards ()):
            # Otherwise, fetch devices.
            self.authconn = answers['_authenticated_connection']
            try:
                self.op = TimedOperation (self.authconn.getDevices,
                                          parent=parent)
                devices = self.op.run ()
                devices_list = []
                for uri, device in devices.items ():
                    if uri.find (':') == -1:
                        continue

                    if device.get('device-class') != 'direct':
                        continue

                    name = device.get('device-info', _("Unknown"))
                    info = device.get('device-make-and-model', _("Unknown"))
                    devices_list.append ((name, info, uri, device))

                devices_list.sort (key=lambda x: x[0])
                for name, info, uri, device in devices_list:
                    iter = model.append (None)
                    model.set (iter, 0, name, 1, info, 2, uri, 3, device)

            except cups.HTTPError:
                pass
            except cups.IPPError:
                pass
            except RuntimeError:
                pass

        if answers['cups_queue_listed']:
            try:
                printer_dict = answers['cups_printer_dict']
                uri = printer_dict['device-uri']
                device = devices[uri]
                self.answers['cups_device_dict'] = device
            except KeyError:
                pass

            return False

        return True

    def connect_signals (self, handler):
        self.signal_id = self.treeview.connect ("cursor-changed", handler)

    def disconnect_signals (self):
        self.treeview.disconnect (self.signal_id)
#.........这里部分代码省略.........
开发者ID:antlarr,项目名称:system-config-printer,代码行数:103,代码来源:DeviceListed.py

示例11: PrinterStateReasons

# 需要导入模块: from timedops import TimedOperation [as 别名]
# 或者: from timedops.TimedOperation import run [as 别名]
class PrinterStateReasons(Question):
    def __init__ (self, troubleshooter):
        Question.__init__ (self, troubleshooter, "Printer state reasons")
        page = self.initial_vbox (_("Status Messages"),
                                  _("There are status messages associated with "
                                    "this queue."))
        self.label = Gtk.Label ()
        self.label.set_alignment (0, 0)
        self.label.set_line_wrap (True)
        page.pack_start (self.label, False, False, 0)

        troubleshooter.new_page (page, self)

    def display (self):
        troubleshooter = self.troubleshooter
        try:
            queue = troubleshooter.answers['cups_queue']
        except KeyError:
            return False

        parent = self.troubleshooter.get_window ()
        cups.setServer ('')
        self.op = TimedOperation (cups.Connection, parent=parent)
        c = self.op.run ()
        self.op = TimedOperation (c.getPrinterAttributes,
                                  args=(queue,),
                                  parent=parent)
        dict = self.op.run ()

        the_ppdcache = ppdcache.PPDCache ()

        text = ''
        state_message = dict['printer-state-message']
        if state_message:
            text += _("The printer's state message is: '%s'.") % state_message
            text += '\n\n'

        state_reasons_list = dict['printer-state-reasons']
        if type (state_reasons_list) == str:
            state_reasons_list = [state_reasons_list]

        self.state_message = state_message
        self.state_reasons = state_reasons_list

        human_readable_errors = []
        human_readable_warnings = []
        for reason in state_reasons_list:
            if reason == "none":
                continue

            r = statereason.StateReason (queue, reason, the_ppdcache)
            (title, description) = r.get_description ()
            level = r.get_level ()
            if level == statereason.StateReason.ERROR:
                human_readable_errors.append (description)
            elif level == statereason.StateReason.WARNING:
                human_readable_warnings.append (description)

        if human_readable_errors:
            text += _("Errors are listed below:") + '\n'
            text += reduce (lambda x, y: x + "\n" + y, human_readable_errors)
            text += '\n\n'

        if human_readable_warnings:
            text += _("Warnings are listed below:") + '\n'
            text += reduce (lambda x, y: x + "\n" + y, human_readable_warnings)

        self.label.set_text (text)
        if (state_message == '' and
            len (human_readable_errors) == 0 and
            len (human_readable_warnings) == 0):
            return False

        # If this screen has been show before, don't show it again if
        # nothing changed.
        if 'printer-state-message' in troubleshooter.answers:
            if (troubleshooter.answers['printer-state-message'] ==
                self.state_message and
                troubleshooter.answers['printer-state-reasons'] ==
                self.state_reasons):
                return False

        return True

    def collect_answer (self):
        if not self.displayed:
            return {}

        return { 'printer-state-message': self.state_message,
                 'printer-state-reasons': self.state_reasons }

    def cancel_operation (self):
        self.op.cancel ()
开发者ID:Distrotech,项目名称:system-config-printer,代码行数:95,代码来源:PrinterStateReasons.py


注:本文中的timedops.TimedOperation.run方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。