简体   繁体   中英

Python str.translate unicode

So I'm creating a python keylogger. I managed to get the differnet modifiers key status when a key is pressed and so I dev a function to for example put letter in caps when shift is pressed and here it is:

def applyKeyModifier(x,shift,ctrl,altgr,win):
    keyboard      = u"""²&é"'(-è_çà)=azertyuiop^$qsdfghjklmù*<wxcvbn,;:!/*-+"""
    shiftModified = u"""_1234567890°+AZERTYUIOP¨£QSDFGHJKLM%µ>WXCVBN?./§/*-+"""
    altgrModified = u"""__~#{[|`\^@]}€__________¤___________________________"""

    shiftTranslation = string.maketrans(keyboard, shiftModified)
    altgrTranslation = string.maketrans(keyboard, altgrModified)
    if shift and not altgr and not ctrl and not win:
        translated = x.translate(shiftTranslation)
        if translated == "_":
            translated=""
        return translated
    elif altgr and not shift and not ctrl and not win:
        translated = x.translate(shiftTranslation)
        if translated == "_":
            translated=""
        return translated
    elif ctrl and not shift and not altgr and not win: 
        return " [CTRL+"+x+"] "
    elif win and not shift and not altgr and not ctrl: 
        return " [WIN/CMD+"+x+"] "
    else:
        return x

The only problem is that I get this error:

C:\Users\tugle\Desktop>python keylogger.py
Traceback (most recent call last):
  File "keylogger.py", line 139, in <module>
    listener.join()
  File "C:\dev\Python27\lib\site-packages\pynput\_util\__init__.py", line 199, in join
    six.reraise(exc_type, exc_value, exc_traceback)
  File "C:\dev\Python27\lib\site-packages\pynput\_util\__init__.py", line 154, in inner
    return f(self, *args, **kwargs)
  File "C:\dev\Python27\lib\site-packages\pynput\keyboard\_win32.py", line 237, in _process
    self.on_press(key)
  File "C:\dev\Python27\lib\site-packages\pynput\_util\__init__.py", line 75, in inner
    if f(*args) is False:
  File "keylogger.py", line 117, in on_press
    keybuffer += applyKeyModifier(str(key),isShift,isCtrl,isAltGr,isWin)
  File "keylogger.py", line 19, in applyKeyModifier
    shiftTranslation = string.maketrans(keyboard, shiftModified)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xb2' in position 0: ordinal not in range(128)

I'm using python2. So can somebody help me here

The translate() method behaves differently depending on whether it's called on a str or a unicode . You're working with non-ASCII characters, so your strings should be unicode objects, and unicode.translate() takes a mapping ( dict ) instead of a maketrans table. Quoth the docs:

For Unicode objects, the translate() method does not accept the optional deletechars argument. Instead, it returns a copy of the s where all characters have been mapped through the given translation table which must be a mapping of Unicode ordinals to Unicode ordinals, Unicode strings or None . Unmapped characters are left untouched. Characters mapped to None are deleted.

Thus, shiftTranslation needs to be of the form:

shiftTranslation = {
    ord(u'²'): u'_',
    ord(u'&'): u'1',
    ord(u'é'): u'2',
    # etc.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM