Search code examples
pythonstringutf-8decodepyperclip

Python pyperclip cannot copy decoded


I just found out that for some reason when copying using pyperclip a string that was decoded (using utf-8), it will raise an error.

import pyperclip
with open('chat.txt' 'r') as f:
    string = f.read()
# the string is encoded in utf-8 in order to be able to write down `'`, `emoji` and other special signs or symbol
pyperclip.copy(string.decode('utf-8'))

It will raise this error: PyperclipException: only str, int, float, and bool values can be copied to the clipboard, not unicode

I found a roundabout way to solve it by using str() but then found out that it won't work since str() does not work if there are some character like '.


EDIT: Alternative solution

An alternative solution except for the solution that I accepted would be degrade the pyperclip from the newest version (right now its 1.6.4) to a lower version (1.6.1 worked for me).


Solution

  • You seem to be facing some issues with non-ASCII quotation marks. I suggest you to use Python 3.7. Here's a sample:

    import pyperclip
    
    with open('chat.txt', 'r') as f:
        string = f.read()
    pyperclip.copy(string)
    

    This is an alternative for Python 2.7:

    import pyperclip
    import sys
    reload(sys)
    sys.setdefaultencoding('utf8')
    
    with open('chat.txt', 'r') as f:
        string = f.read()
    
    pyperclip.copy(string)
    

    Warning: As pointed out in a comment by @lenz the use of sys.setdefaultencoding() is a hack and discouraged for a number of reasons.