Python脚本在Autokey上不起作用

2024-06-07 00:44:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在Python上制作一个html实体编码器/解码器,它的行为类似于PHP的htmlentities和{},它通常作为一个独立的脚本工作:

我的输入:

Lorem ÁÉÍÓÚÇÃOÁáéíóúção @#$%*()[]<>+ 0123456789

python decode.py

输出:

^{pr2}$

现在,如果我将其作为自动键脚本运行,则会出现以下错误:

Script name: 'html_entity_decode'
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/autokey/service.py", line 454, in execute
    exec script.code in scope
  File "<string>", line 40, in <module>
  File "/usr/local/lib/python2.7/dist-packages/autokey/scripting.py", line 42, in send_keys
    self.mediator.send_string(keyString.decode("utf-8"))
  File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
    return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 6-12: ordinal not in range(128)

我做错什么了?脚本如下:

import htmlentitydefs
import re

entity_re = re.compile(r'&(%s|#(\d{1,5}|[xX]([\da-fA-F]{1,4})));' % '|'.join(
    htmlentitydefs.name2codepoint.keys()))

def html_entity_decode(s, encoding='utf-8'):

    if not isinstance(s, basestring):
        raise TypeError('argument 1: expected string, %s found' \
                        % s.__class__.__name__)

    def entity_2_unichr(matchobj):
        g1, g2, g3 = matchobj.groups()
        if g3 is not None:
            codepoint = int(g3, 16)
        elif g2 is not None:
            codepoint = int(g2)
        else:
            codepoint = htmlentitydefs.name2codepoint[g1]
        return unichr(codepoint)

    if isinstance(s, unicode):
        entity_2_chr = entity_2_unichr
    else:
        entity_2_chr = lambda o: entity_2_unichr(o).encode(encoding,
                                                           'xmlcharrefreplace')
    def silent_entity_replace(matchobj):
        try:
            return entity_2_chr(matchobj)
        except ValueError:
            return matchobj.group(0)

    return entity_re.sub(silent_entity_replace, s)

text = clipboard.get_selection()
text = html_entity_decode(text)
keyboard.send_keys("%s" % text)

我在一个要点上找到的,我不是作者。在


Tags: textinpyrereturnhtmllinenot
2条回答

问题在于:

clipboard.get_selection()

是unicode字符串。在

要解决此问题,请更换:

^{pr2}$

签署人:

text = clipboard.get_selection().encode("utf8")

查看回溯跟踪,可能的问题是您正在将一个unicode字符串传递给键盘.发送键,它需要由testring编码的UTF-8。然后,autokey尝试解码字符串,但由于输入的是unicode而不是utf-8,所以失败了。这看起来像是autokey中的一个bug:除非字符串是真正的纯(byte)sstring,否则不应该尝试对字符串进行解码。在

如果这个猜测是正确的,那么您应该能够通过一个unicode实例来发送密钥来解决这个问题。试试这样的方法:

text = clipboard.get_selection()
if isinstance(text, unicode):
    text = text.encode('utf-8')
text = html_entity_decode(text)
assert isinstance(text, str)
keyboard.send_keys(text)

不需要assert,但它是一个方便的健全性检查,以确保html_entity_decode执行正确的操作。在

相关问题 更多 >