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


Python compat.text_type函数代码示例

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


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

示例1: send_feedback

def send_feedback(dsn, event_id, name, email, comment, timeout):
    """Send feedback, blocking.

    Args:
        dsn (str): The DSN
        event_id (str): The event ID this feedback should be attached to
        name (text_type): The user name
        email (text_type): The user email
        comment (text_type): The feedback text
        timeout (float): The timeout for this request
    Raises:
        SentryError: In case of timeout or other errors
    """

    name = text_type(name).encode("utf-8")
    email = text_type(email).encode("utf-8")
    comment = text_type(comment).encode("utf-8")

    data = urlencode(
        [('name', name), ('email', email), ('comments', comment)])
    if not isinstance(data, bytes):
        # py3
        data = data.encode("utf-8")

    headers = {"Referer": "https://quodlibet.github.io"}
    params = urlencode([("dsn", dsn), ("eventId", event_id)])

    try:
        req = Request(
            "https://sentry.io/api/embed/error-page/?" + params,
            data=data, headers=headers)

        urlopen(req, timeout=timeout).close()
    except EnvironmentError as e:
        raise SentryError(e)
开发者ID:elfalem,项目名称:quodlibet,代码行数:35,代码来源:sentrywrapper.py

示例2: __init__

    def __init__(self, filename):
        with translate_errors():
            audio = Musepack(filename)

        super(MPCFile, self).__init__(filename, audio)
        self["~#length"] = audio.info.length
        self["~#bitrate"] = int(audio.info.bitrate / 1000)

        version = audio.info.version
        self["~codec"] = u"%s SV%d" % (self.format, version)

        try:
            if audio.info.title_gain:
                track_g = u"%+0.2f dB" % audio.info.title_gain
                self.setdefault("replaygain_track_gain", track_g)
            if audio.info.album_gain:
                album_g = u"%+0.2f dB" % audio.info.album_gain
                self.setdefault("replaygain_album_gain", album_g)
            if audio.info.title_peak:
                track_p = text_type(audio.info.title_peak * 2)
                self.setdefault("replaygain_track_peak", track_p)
            if audio.info.album_peak:
                album_p = text_type(audio.info.album_peak * 2)
                self.setdefault("replaygain_album_peak", album_p)
        except AttributeError:
            pass

        self.sanitize(filename)
开发者ID:bernd-wechner,项目名称:quodlibet,代码行数:28,代码来源:mpc.py

示例3: _execute

    def _execute(self, options, args):
        if len(args) < 1:
            raise CommandError(_("Not enough arguments"))
        elif len(args) > 1:
            raise CommandError(_("Too many arguments"))

        path = args[0]
        song = self.load_song(path)

        headers = [_("Description"), _("Value")]
        nicks = ["desc", "value"]

        if not options.columns:
            order = nicks
        else:
            order = [n.strip() for n in options.columns.split(",")]

        if not options.terse:
            tags = []
            for key in ["~format", "~codec", "~encoding", "~length",
                        "~bitrate", "~filesize"]:
                tags.append((util.tag(key), text_type(song.comma(key))))

            print_table(tags, headers, nicks, order)
        else:
            tags = []
            for key in ["~format", "~codec", "~encoding", "~#length",
                        "~#bitrate", "~#filesize"]:
                tags.append((key.lstrip("#~"), text_type(song(key))))

            print_terse_table(tags, nicks, order)
开发者ID:LudoBike,项目名称:quodlibet,代码行数:31,代码来源:commands.py

示例4: upgettext

 def upgettext(self, context, msgid):
     context = text_type(context)
     msgid = text_type(msgid)
     real_msgid = u"%s\x04%s" % (context, msgid)
     result = self.ugettext(real_msgid)
     if result == real_msgid:
         return msgid
     return result
开发者ID:urielz,项目名称:quodlibet,代码行数:8,代码来源:i18n.py

示例5: ugettext

 def ugettext(self, message):
     # force unicode here since __contains__ (used in gettext) ignores
     # our changed defaultencoding for coercion, so utf-8 encoded strings
     # fail at lookup.
     message = text_type(message)
     if PY2:
         return text_type(gettext.GNUTranslations.ugettext(self, message))
     else:
         return text_type(gettext.GNUTranslations.gettext(self, message))
开发者ID:urielz,项目名称:quodlibet,代码行数:9,代码来源:i18n.py

示例6: ungettext

 def ungettext(self, msgid1, msgid2, n):
     # see ugettext
     msgid1 = text_type(msgid1)
     msgid2 = text_type(msgid2)
     if PY2:
         return text_type(
             gettext.GNUTranslations.ungettext(self, msgid1, msgid2, n))
     else:
         return text_type(
             gettext.GNUTranslations.ngettext(self, msgid1, msgid2, n))
开发者ID:urielz,项目名称:quodlibet,代码行数:10,代码来源:i18n.py

示例7: unpgettext

 def unpgettext(self, context, msgid, msgidplural, n):
     context = text_type(context)
     msgid = text_type(msgid)
     msgidplural = text_type(msgidplural)
     real_msgid = u"%s\x04%s" % (context, msgid)
     real_msgidplural = u"%s\x04%s" % (context, msgidplural)
     result = self.ngettext(real_msgid, real_msgidplural, n)
     if result == real_msgid:
         return msgid
     elif result == real_msgidplural:
         return msgidplural
     return result
开发者ID:urielz,项目名称:quodlibet,代码行数:12,代码来源:i18n.py

示例8: __init__

    def __init__(self, pattern, mod_string):
        self.pattern = text_type(pattern)
        self.mod_string = text_type(mod_string)

        ignore_case = "c" not in self.mod_string or "i" in self.mod_string
        dot_all = "s" in self.mod_string
        asym = "d" in self.mod_string
        try:
            self.search = compile(self.pattern, ignore_case, dot_all, asym)
        except ValueError:
            raise ParseError(
                "The regular expression /%s/ is invalid." % self.pattern)
开发者ID:LudoBike,项目名称:quodlibet,代码行数:12,代码来源:_match.py

示例9: setstringlist

    def setstringlist(self, section, option, values):
        """Saves a list of unicode strings using the csv module"""

        if PY2:
            sw = cBytesIO()
            values = [text_type(v).encode('utf-8') for v in values]
        else:
            sw = StringIO()
            values = [text_type(v) for v in values]

        writer = csv.writer(sw, lineterminator='\n', quoting=csv.QUOTE_MINIMAL)
        writer.writerow(values)
        self.set(section, option, sw.getvalue())
开发者ID:ZDBioHazard,项目名称:quodlibet,代码行数:13,代码来源:config.py

示例10: decode_value

def decode_value(tag, value):
    """Returns a unicode representation of the passed value, based on
    the type and the tag it originated from.

    Not reversible.
    """

    if tag in FILESYSTEM_TAGS:
        return fsn2text(value)
    elif tag[:2] == "~#":
        if isinstance(value, float):
            return u"%.2f" % value
        else:
            return text_type(value)
    return text_type(value)
开发者ID:elfalem,项目名称:quodlibet,代码行数:15,代码来源:_audio.py

示例11: get_grouping_key

    def get_grouping_key(self):
        """Given a stacktrace produced by the faulthandler module returns a
        short string for grouping similar stacktraces together.

        Args:
            stacktrace (text_type)
        Returns:
            text_type
        """

        stacktrace = text_type(self)
        if isinstance(stacktrace, bytes):
            stacktrace = stacktrace.decode("utf-8", "replace")

        assert isinstance(stacktrace, text_type)

        # Extract the basename and the function name for each line and hash
        # them. Could be smarter, but let's try this for now..
        reg = re.compile(r'.*?"([^"]+).*?(\w+$)')
        values = []
        for l in stacktrace.splitlines():
            m = reg.match(l)
            if m is not None:
                path, func = m.groups()
                path = os.path.basename(path)
                values.extend([path, func])
        return u"|".join(values)
开发者ID:LudoBike,项目名称:quodlibet,代码行数:27,代码来源:faulthandling.py

示例12: add_station

def add_station(uri):
    """Fetches the URI content and extracts IRFiles
    Returns None in error, else a possibly filled list of stations"""

    irfs = []

    if uri.lower().endswith(".pls") or uri.lower().endswith(".m3u"):
        try:
            sock = urlopen(uri)
        except EnvironmentError as err:
            err = text_type(err)
            print_d("Got %s from %s" % (uri, err))
            ErrorMessage(None, _("Unable to add station"), escape(err)).run()
            return None

        if uri.lower().endswith(".pls"):
            irfs = ParsePLS(sock)
        elif uri.lower().endswith(".m3u"):
            irfs = ParseM3U(sock)

        sock.close()
    else:
        try:
            irfs = [IRFile(uri)]
        except ValueError as err:
            ErrorMessage(None, _("Unable to add station"), err).run()

    return irfs
开发者ID:elfalem,项目名称:quodlibet,代码行数:28,代码来源:iradio.py

示例13: _try_build_device

    def _try_build_device(self, object_path, block, fs):
        """Returns a Device instance or None.

        None if it wasn't a media player etc..
        """

        drive = self._drives.get(block["Drive"])
        if not drive:
            # I think this shouldn't happen, but check anyway
            return

        dev_path = dbus_barray_to_bytes(block["Device"])
        print_d("Found device: %r" % dev_path)

        media_player_id = get_media_player_id(self._udev, dev_path)
        if not media_player_id:
            print_d("%r not a media player" % dev_path)
            return
        protocols = get_media_player_protocols(media_player_id)

        device_id = drive["Id"]

        dev = self.create_device(object_path, text_type(device_id), protocols)
        icon_name = block["HintIconName"]
        if icon_name:
            dev.icon = icon_name
        return dev
开发者ID:ZDBioHazard,项目名称:quodlibet,代码行数:27,代码来源:__init__.py

示例14: plugin_songs

 def plugin_songs(self, songs):
     # Check this is a launch, not a configure
     if self.chosen_site:
         url_pat = self.get_url_pattern(self.chosen_site)
         pat = Pattern(url_pat)
         urls = set()
         for song in songs:
             # Generate a sanitised AudioFile; allow through most tags
             subs = AudioFile()
             for k in (USER_TAGS + MACHINE_TAGS):
                 vals = song.comma(k)
                 if vals:
                     try:
                         encoded = text_type(vals).encode('utf-8')
                         subs[k] = (encoded if k == 'website'
                                    else quote_plus(encoded))
                     # Dodgy unicode problems
                     except KeyError:
                         print_d("Problem with %s tag values: %r"
                                 % (k, vals))
             url = str(pat.format(subs))
             if not url:
                 print_w("Couldn't build URL using \"%s\"."
                         "Check your pattern?" % url_pat)
                 return
             # Grr, set.add() should return boolean...
             if url not in urls:
                 urls.add(url)
                 website(url)
开发者ID:elfalem,项目名称:quodlibet,代码行数:29,代码来源:website_search.py

示例15: __init__

    def __init__(self, filename):
        with translate_errors():
            audio = MP4(filename)
        self["~codec"] = audio.info.codec_description
        self["~#length"] = audio.info.length
        self["~#bitrate"] = int(audio.info.bitrate / 1000)
        if audio.info.channels:
            self["~#channels"] = audio.info.channels
        self["~#samplerate"] = audio.info.sample_rate
        self["~#bitdepth"] = audio.info.bits_per_sample

        for key, values in audio.items():
            if key in self.__tupletranslate:
                if values:
                    name = self.__tupletranslate[key]
                    cur, total = values[0]
                    if total:
                        self[name] = u"%d/%d" % (cur, total)
                    else:
                        self[name] = text_type(cur)
            elif key in self.__translate:
                name = self.__translate[key]
                if key == "tmpo":
                    self[name] = u"\n".join(map(text_type, values))
                elif key.startswith("----"):
                    self[name] = "\n".join(
                        map(lambda v: decode(v).strip("\x00"), values))
                else:
                    self[name] = "\n".join(values)
            elif key == "covr":
                self.has_images = True
        self.sanitize(filename)
开发者ID:LudoBike,项目名称:quodlibet,代码行数:32,代码来源:mp4.py


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