• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python message.error函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中qutebrowser.utils.message.error函数的典型用法代码示例。如果您正苦于以下问题:Python error函数的具体用法?Python error怎么用?Python error使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: edit

    def edit(self, text):
        """Edit a given text.

        Args:
            text: The initial text to edit.
        """
        if self._text is not None:
            raise ValueError("Already editing a file!")
        self._text = text
        encoding = config.get('general', 'editor-encoding')
        try:
            # Close while the external process is running, as otherwise systems
            # with exclusive write access (e.g. Windows) may fail to update
            # the file from the external editor, see
            # https://github.com/The-Compiler/qutebrowser/issues/1767
            with tempfile.NamedTemporaryFile(
                    mode='w', prefix='qutebrowser-editor-', encoding=encoding,
                    delete=False) as fobj:
                if text:
                    fobj.write(text)
                self._file = fobj
        except OSError as e:
            message.error("Failed to create initial file: {}".format(e))
            return
        self._proc = guiprocess.GUIProcess(what='editor', parent=self)
        self._proc.finished.connect(self.on_proc_closed)
        self._proc.error.connect(self.on_proc_error)
        editor = config.get('general', 'editor')
        executable = editor[0]
        args = [arg.replace('{}', self._file.name) for arg in editor[1:]]
        log.procs.debug("Calling \"{}\" with args {}".format(executable, args))
        self._proc.start(executable, args)
开发者ID:Dietr1ch,项目名称:qutebrowser,代码行数:32,代码来源:editor.py


示例2: on_proc_closed

    def on_proc_closed(self, exitcode, exitstatus):
        """Write the editor text into the form field and clean up tempfile.

        Callback for QProcess when the editor was closed.
        """
        log.procs.debug("Editor closed")
        if exitstatus != QProcess.NormalExit:
            # No error/cleanup here, since we already handle this in
            # on_proc_error.
            return
        try:
            if exitcode != 0:
                return
            encoding = config.get('general', 'editor-encoding')
            try:
                with open(self._filename, 'r', encoding=encoding) as f:
                    text = f.read()  # pragma: no branch
            except OSError as e:
                # NOTE: Do not replace this with "raise CommandError" as it's
                # executed async.
                message.error(self._win_id, "Failed to read back edited file: "
                                            "{}".format(e))
                return
            log.procs.debug("Read back: {}".format(text))
            self.editing_finished.emit(text)
        finally:
            self._cleanup()
开发者ID:shawa,项目名称:qutebrowser,代码行数:27,代码来源:editor.py


示例3: quickmark_add

    def quickmark_add(self, win_id, url, name):
        """Add a new quickmark.

        Args:
            win_id: The window ID to display the errors in.
            url: The url to add as quickmark.
            name: The name for the new quickmark.
        """
        # We don't raise cmdexc.CommandError here as this can be called async
        # via prompt_save.
        if not name:
            message.error(win_id, "Can't set mark with empty name!")
            return
        if not url:
            message.error(win_id, "Can't set mark with empty URL!")
            return

        def set_mark():
            """Really set the quickmark."""
            self.marks[name] = url
            self.changed.emit()
            self.added.emit(name, url)

        if name in self.marks:
            message.confirm_async(
                win_id, "Override existing quickmark?", set_mark, default=True)
        else:
            set_mark()
开发者ID:Liambeguin,项目名称:qutebrowser,代码行数:28,代码来源:urlmarks.py


示例4: _process_args

def _process_args(args):
    """Open startpage etc. and process commandline args."""
    config_obj = objreg.get('config')
    for sect, opt, val in args.temp_settings:
        try:
            config_obj.set('temp', sect, opt, val)
        except (configexc.Error, configparser.Error) as e:
            message.error("set: {} - {}".format(e.__class__.__name__, e))

    if not args.override_restore:
        _load_session(args.session)
    session_manager = objreg.get('session-manager')
    if not session_manager.did_load:
        log.init.debug("Initializing main window...")
        window = mainwindow.MainWindow()
        if not args.nowindow:
            window.show()
        qApp.setActiveWindow(window)

    process_pos_args(args.command)
    _open_startpage()
    _open_quickstart(args)

    delta = datetime.datetime.now() - earlyinit.START_TIME
    log.init.debug("Init finished after {}s".format(delta.total_seconds()))
开发者ID:cosminadrianpopescu,项目名称:qutebrowser,代码行数:25,代码来源:app.py


示例5: message_error

def message_error(text):
    """Show an error message in the statusbar.

    Args:
        text: The text to show.
    """
    message.error(text)
开发者ID:lahwaacz,项目名称:qutebrowser,代码行数:7,代码来源:utilcmds.py


示例6: fire

    def fire(self, keystr, force=False):
        """Fire a completed hint.

        Args:
            keystr: The keychain string to follow.
            force: When True, follow even when auto-follow is false.
        """
        if not (force or config.get('hints', 'auto-follow')):
            self.handle_partial_key(keystr)
            self._context.to_follow = keystr
            return
        # Handlers which take a QWebElement
        elem_handlers = {
            Target.normal: self._click,
            Target.current: self._click,
            Target.tab: self._click,
            Target.tab_fg: self._click,
            Target.tab_bg: self._click,
            Target.window: self._click,
            Target.hover: self._click,
            # _download needs a QWebElement to get the frame.
            Target.download: self._download,
            Target.userscript: self._call_userscript,
        }
        # Handlers which take a QUrl
        url_handlers = {
            Target.yank: self._yank,
            Target.yank_primary: self._yank,
            Target.run: self._run_cmd,
            Target.fill: self._preset_cmd_text,
            Target.spawn: self._spawn,
        }
        elem = self._context.elems[keystr].elem
        if elem.webFrame() is None:
            message.error(self._win_id,
                          "This element has no webframe.",
                          immediately=True)
            return
        if self._context.target in elem_handlers:
            handler = functools.partial(elem_handlers[self._context.target],
                                        elem, self._context)
        elif self._context.target in url_handlers:
            url = self._resolve_url(elem, self._context.baseurl)
            if url is None:
                self._show_url_error()
                return
            handler = functools.partial(url_handlers[self._context.target],
                                        url, self._context)
        else:
            raise ValueError("No suitable handler found!")
        if not self._context.rapid:
            modeman.maybe_leave(self._win_id, usertypes.KeyMode.hint,
                                'followed')
        else:
            # Reset filtering
            self.filter_hints(None)
            # Undo keystring highlighting
            for string, elem in self._context.elems.items():
                elem.label.setInnerXml(string)
        handler()
开发者ID:djfinlay,项目名称:qutebrowser,代码行数:60,代码来源:hints.py


示例7: search

    def search(self, text, flags):
        """Search for text in the current page.

        Args:
            text: The text to search for.
            flags: The QWebPage::FindFlags.
        """
        log.webview.debug("Searching with text '{}' and flags "
                          "0x{:04x}.".format(text, int(flags)))
        widget = self.currentWidget()
        old_scroll_pos = widget.scroll_pos
        found = widget.findText(text, flags)
        if not found and not flags & QWebPage.HighlightAllOccurrences and text:
            message.error(self._win_id, "Text '{}' not found on "
                          "page!".format(text), immediately=True)
        else:
            backward = int(flags) & QWebPage.FindBackward

            def check_scroll_pos():
                """Check if the scroll position got smaller and show info."""
                if not backward and widget.scroll_pos < old_scroll_pos:
                    message.info(self._win_id, "Search hit BOTTOM, continuing "
                                 "at TOP", immediately=True)
                elif backward and widget.scroll_pos > old_scroll_pos:
                    message.info(self._win_id, "Search hit TOP, continuing at "
                                 "BOTTOM", immediately=True)
            # We first want QWebPage to refresh.
            QTimer.singleShot(0, check_scroll_pos)
开发者ID:HalosGhost,项目名称:qutebrowser,代码行数:28,代码来源:tabbedbrowser.py


示例8: _move_data

def _move_data(old, new):
    """Migrate data from an old to a new directory.

    If the old directory does not exist, the migration is skipped.
    If the new directory already exists, an error is shown.

    Return: True if moving succeeded, False otherwise.
    """
    if not os.path.exists(old):
        return False

    log.init.debug("Migrating data from {} to {}".format(old, new))

    if os.path.exists(new):
        if not os.path.isdir(new) or os.listdir(new):
            message.error("Failed to move data from {} as {} is non-empty!"
                          .format(old, new))
            return False
        os.rmdir(new)

    try:
        shutil.move(old, new)
    except OSError as e:
        message.error("Failed to move data from {} to {}: {}".format(
            old, new, e))
        return False

    return True
开发者ID:Harrison97,项目名称:qutebrowser,代码行数:28,代码来源:standarddir.py


示例9: adblock_update

 def adblock_update(self, win_id: {'special': 'win_id'}):
     """Update the adblock block lists."""
     self.blocked_hosts = set()
     self._done_count = 0
     urls = config.get('content', 'host-block-lists')
     download_manager = objreg.get('download-manager', scope='window',
                                   window='last-focused')
     if urls is None:
         return
     for url in urls:
         if url.scheme() == 'file':
             try:
                 fileobj = open(url.path(), 'rb')
             except OSError as e:
                 message.error(win_id, "adblock: Error while reading {}: "
                               "{}".format(url.path(), e.strerror))
                 continue
             download = FakeDownload(fileobj)
             self._in_progress.append(download)
             self.on_download_finished(download)
         else:
             fobj = io.BytesIO()
             fobj.name = 'adblock: ' + url.host()
             download = download_manager.get(url, fileobj=fobj,
                                             auto_remove=True)
             self._in_progress.append(download)
             download.finished.connect(
                 functools.partial(self.on_download_finished, download))
开发者ID:JIVS,项目名称:qutebrowser,代码行数:28,代码来源:adblock.py


示例10: _start_cb

    def _start_cb(self, elems):
        """Initialize the elements and labels based on the context set."""
        filterfunc = webelem.FILTERS.get(self._context.group, lambda e: True)
        elems = [e for e in elems if filterfunc(e)]
        if not elems:
            message.error(self._win_id, "No elements found.", immediately=True)
            return
        strings = self._hint_strings(elems)
        log.hints.debug("hints: {}".format(', '.join(strings)))

        for elem, string in zip(elems, strings):
            label = HintLabel(elem, self._context)
            label.update_text('', string)
            self._context.all_labels.append(label)
            self._context.labels[string] = label

        keyparsers = objreg.get('keyparsers', scope='window',
                                window=self._win_id)
        keyparser = keyparsers[usertypes.KeyMode.hint]
        keyparser.update_bindings(strings)

        message_bridge = objreg.get('message-bridge', scope='window',
                                    window=self._win_id)
        message_bridge.set_text(self._get_text())
        modeman.enter(self._win_id, usertypes.KeyMode.hint,
                      'HintManager.start')

        # to make auto-follow == 'always' work
        self._handle_auto_follow()
开发者ID:julianuu,项目名称:qutebrowser,代码行数:29,代码来源:hints.py


示例11: on_proc_closed

    def on_proc_closed(self, exitcode, exitstatus):
        """Write the editor text into the form field and clean up tempfile.

        Callback for QProcess when the editor was closed.
        """
        log.procs.debug("Editor closed")
        if exitstatus != QProcess.NormalExit:
            # No error/cleanup here, since we already handle this in
            # on_proc_error
            return
        try:
            if exitcode != 0:
                # NOTE: Do not replace this with "raise CommandError" as it's
                # executed async.
                message.error(
                    self._win_id, "Editor did quit abnormally (status "
                                  "{})!".format(exitcode))
                return
            encoding = config.get('general', 'editor-encoding')
            with open(self._filename, 'r', encoding=encoding) as f:
                text = ''.join(f.readlines())
            log.procs.debug("Read back: {}".format(text))
            self.editing_finished.emit(text)
        finally:
            self._cleanup()
开发者ID:anweshknayak,项目名称:qutebrowser,代码行数:25,代码来源:editor.py


示例12: _on_link_clicked

    def _on_link_clicked(self, url):
        log.webview.debug("link clicked: url {}, hint target {}, "
                          "open_target {}".format(
                              url.toDisplayString(),
                              self.data.hint_target, self.data.open_target))

        if not url.isValid():
            msg = urlutils.get_errstring(url, "Invalid link clicked")
            message.error(self.win_id, msg)
            self.data.open_target = usertypes.ClickTarget.normal
            return False

        target = self.data.combined_target()

        if target == usertypes.ClickTarget.normal:
            return
        elif target == usertypes.ClickTarget.tab:
            win_id = self.win_id
            bg_tab = False
        elif target == usertypes.ClickTarget.tab_bg:
            win_id = self.win_id
            bg_tab = True
        elif target == usertypes.ClickTarget.window:
            from qutebrowser.mainwindow import mainwindow
            window = mainwindow.MainWindow()
            window.show()
            win_id = window.win_id
            bg_tab = False
        else:
            raise ValueError("Invalid ClickTarget {}".format(target))

        tabbed_browser = objreg.get('tabbed-browser', scope='window',
                                    window=win_id)
        tabbed_browser.tabopen(url, background=bg_tab)
        self.data.open_target = usertypes.ClickTarget.normal
开发者ID:meles5,项目名称:qutebrowser,代码行数:35,代码来源:browsertab.py


示例13: _prevnext_cb

    def _prevnext_cb(elems):
        elem = _find_prevnext(prev, elems)
        word = 'prev' if prev else 'forward'

        if elem is None:
            message.error(win_id, "No {} links found!".format(word))
            return
        url = elem.resolve_url(baseurl)
        if url is None:
            message.error(win_id, "No {} links found!".format(word))
            return
        qtutils.ensure_valid(url)

        if window:
            from qutebrowser.mainwindow import mainwindow
            new_window = mainwindow.MainWindow()
            new_window.show()
            tabbed_browser = objreg.get('tabbed-browser', scope='window',
                                        window=new_window.win_id)
            tabbed_browser.tabopen(url, background=False)
        elif tab:
            tabbed_browser = objreg.get('tabbed-browser', scope='window',
                                        window=win_id)
            tabbed_browser.tabopen(url, background=background)
        else:
            browsertab.openurl(url)
开发者ID:meles5,项目名称:qutebrowser,代码行数:26,代码来源:navigate.py


示例14: _open_startpage

def _open_startpage(win_id=None):
    """Open startpage.

    The startpage is never opened if the given windows are not empty.

    Args:
        win_id: If None, open startpage in all empty windows.
                If set, open the startpage in the given window.
    """
    if win_id is not None:
        window_ids = [win_id]
    else:
        window_ids = objreg.window_registry
    for cur_win_id in window_ids:
        tabbed_browser = objreg.get("tabbed-browser", scope="window", window=cur_win_id)
        if tabbed_browser.count() == 0:
            log.init.debug("Opening startpage")
            for urlstr in config.get("general", "startpage"):
                try:
                    url = urlutils.fuzzy_url(urlstr, do_search=False)
                except urlutils.InvalidUrlError as e:
                    message.error("current", "Error when opening startpage: " "{}".format(e))
                    tabbed_browser.tabopen(QUrl("about:blank"))
                else:
                    tabbed_browser.tabopen(url)
开发者ID:Link-Satonaka,项目名称:qutebrowser,代码行数:25,代码来源:app.py


示例15: on_ssl_errors

    def on_ssl_errors(self, reply, errors):
        """Decide if SSL errors should be ignored or not.

        This slot is called on SSL/TLS errors by the self.sslErrors signal.

        Args:
            reply: The QNetworkReply that is encountering the errors.
            errors: A list of errors.
        """
        ssl_strict = config.get('network', 'ssl-strict')
        if ssl_strict == 'ask':
            err_string = '\n'.join('- ' + err.errorString() for err in errors)
            answer = self._ask(self._win_id,
                               'SSL errors - continue?\n{}'.format(err_string),
                               mode=usertypes.PromptMode.yesno,
                               owners=(reply,))
            if answer:
                reply.ignoreSslErrors()
        elif ssl_strict:
            pass
        else:
            for err in errors:
                # FIXME we might want to use warn here (non-fatal error)
                # https://github.com/The-Compiler/qutebrowser/issues/114
                message.error(self._win_id,
                              'SSL error: {}'.format(err.errorString()))
            reply.ignoreSslErrors()
开发者ID:shaggytwodope,项目名称:aur,代码行数:27,代码来源:networkmanager.py


示例16: _on_finished

    def _on_finished(self, code, status):
        """Show a message when the process finished."""
        self._started = False
        log.procs.debug("Process finished with code {}, status {}.".format(
            code, status))

        encoding = locale.getpreferredencoding(do_setlocale=False)
        stderr = bytes(self._proc.readAllStandardError()).decode(
            encoding, 'replace')
        stdout = bytes(self._proc.readAllStandardOutput()).decode(
            encoding, 'replace')

        if status == QProcess.CrashExit:
            exitinfo = "{} crashed!".format(self._what.capitalize())
            message.error(exitinfo)
        elif status == QProcess.NormalExit and code == 0:
            exitinfo = "{} exited successfully.".format(
                self._what.capitalize())
            if self.verbose:
                message.info(exitinfo)
        else:
            assert status == QProcess.NormalExit
            # We call this 'status' here as it makes more sense to the user -
            # it's actually 'code'.
            exitinfo = ("{} exited with status {}, see :messages for "
                        "details.").format(self._what.capitalize(), code)
            message.error(exitinfo)

            if stdout:
                log.procs.error("Process stdout:\n" + stdout.strip())
            if stderr:
                log.procs.error("Process stderr:\n" + stderr.strip())

        qutescheme.spawn_output = self._spawn_format(exitinfo, stdout, stderr)
开发者ID:The-Compiler,项目名称:qutebrowser,代码行数:34,代码来源:guiprocess.py


示例17: _hint_strings

    def _hint_strings(self, elems):
        """Calculate the hint strings for elems.

        Inspired by Vimium.

        Args:
            elems: The elements to get hint strings for.

        Return:
            A list of hint strings, in the same order as the elements.
        """
        hint_mode = config.get('hints', 'mode')
        if hint_mode == 'word':
            try:
                return self._word_hinter.hint(elems)
            except WordHintingError as e:
                message.error(self._win_id, str(e), immediately=True)
                # falls back on letter hints
        if hint_mode == 'number':
            chars = '0123456789'
        else:
            chars = config.get('hints', 'chars')
        min_chars = config.get('hints', 'min-chars')
        if config.get('hints', 'scatter') and hint_mode != 'number':
            return self._hint_scattered(min_chars, chars, elems)
        else:
            return self._hint_linear(min_chars, chars, elems)
开发者ID:djfinlay,项目名称:qutebrowser,代码行数:27,代码来源:hints.py


示例18: _set_download_target

    def _set_download_target(self, download, suggested_filename, target):
        """Set the target for a given download.

        Args:
            download: The download to set the filename for.
            suggested_filename: The suggested filename.
            target: The usertypes.DownloadTarget for this download.
        """
        if isinstance(target, usertypes.FileObjDownloadTarget):
            download.set_fileobj(target.fileobj)
            download.autoclose = False
        elif isinstance(target, usertypes.FileDownloadTarget):
            download.set_filename(target.filename)
        elif isinstance(target, usertypes.OpenFileDownloadTarget):
            tmp_manager = objreg.get('temporary-downloads')
            try:
                fobj = tmp_manager.get_tmpfile(suggested_filename)
            except OSError as exc:
                msg = "Download error: {}".format(exc)
                message.error(self._win_id, msg)
                download.cancel()
                return
            download.finished.connect(
                functools.partial(self._open_download, download))
            download.autoclose = True
            download.set_fileobj(fobj)
        else:
            log.downloads.error("Unknown download target: {}".format(target))
开发者ID:LadyClaire,项目名称:qutebrowser,代码行数:28,代码来源:downloads.py


示例19: qute_help

def qute_help(win_id, request):
    """Handler for qute:help. Return HTML content as bytes."""
    try:
        utils.read_file('html/doc/index.html')
    except FileNotFoundError:
        html = jinja.env.get_template('error.html').render(
            title="Error while loading documentation",
            url=request.url().toDisplayString(),
            error="This most likely means the documentation was not generated "
                  "properly. If you are running qutebrowser from the git "
                  "repository, please run scripts/asciidoc2html.py."
                  "If you're running a released version this is a bug, please "
                  "use :report to report it.",
            icon='')
        return html.encode('UTF-8', errors='xmlcharrefreplace')
    urlpath = request.url().path()
    if not urlpath or urlpath == '/':
        urlpath = 'index.html'
    else:
        urlpath = urlpath.lstrip('/')
    if not docutils.docs_up_to_date(urlpath):
        message.error(win_id, "Your documentation is outdated! Please re-run "
                      "scripts/asciidoc2html.py.")
    path = 'html/doc/{}'.format(urlpath)
    return utils.read_file(path).encode('UTF-8', errors='xmlcharrefreplace')
开发者ID:JIVS,项目名称:qutebrowser,代码行数:25,代码来源:qutescheme.py


示例20: edit

    def edit(self, text, caret_position=0):
        """Edit a given text.

        Args:
            text: The initial text to edit.
            caret_position: The position of the caret in the text.
        """
        if self._filename is not None:
            raise ValueError("Already editing a file!")
        try:
            # Close while the external process is running, as otherwise systems
            # with exclusive write access (e.g. Windows) may fail to update
            # the file from the external editor, see
            # https://github.com/qutebrowser/qutebrowser/issues/1767
            with tempfile.NamedTemporaryFile(
                    mode='w', prefix='qutebrowser-editor-',
                    encoding=config.val.editor.encoding,
                    delete=False) as fobj:
                if text:
                    fobj.write(text)
                self._filename = fobj.name
        except OSError as e:
            message.error("Failed to create initial file: {}".format(e))
            return

        self._remove_file = True

        line, column = self._calc_line_and_column(text, caret_position)
        self._start_editor(line=line, column=column)
开发者ID:blyxxyz,项目名称:qutebrowser,代码行数:29,代码来源:editor.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python message.info函数代码示例发布时间:2022-05-26
下一篇:
Python message.ask函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap