Python pyperclip无法复制已解码的文件

Python pyperclip无法复制已解码的文件,python,string,utf-8,decode,pyperclip,Python,String,Utf 8,Decode,Pyperclip,我刚刚发现,出于某种原因,当使用pyperclip复制使用utf-8解码的字符串时,它会引发错误 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(s

我刚刚发现,出于某种原因,当使用pyperclip复制使用utf-8解码的字符串时,它会引发错误

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'))
它将引发此错误:PyperclipException:只能将str、int、float和bool值复制到剪贴板,而不能复制到unicode

我找到了一种迂回的方法,通过使用str来解决这个问题,但后来发现它不起作用,因为如果有像'这样的字符,str就不起作用

编辑:替代解决方案


除了我接受的解决方案之外,另一种解决方案是将pyperclip从目前最新版本(1.6.4)降级为较低版本(1.6.1)。您似乎面临一些非ASCII引号的问题。我建议您使用Python 3.7。以下是一个示例:

import pyperclip

with open('chat.txt', 'r') as f:
    string = f.read()
pyperclip.copy(string)
这是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)

警告:@lenz在评论中指出,使用sys.setdefaultencoding是一种黑客行为,不鼓励使用。此问题已在1.6.5中修复,因此,您所要做的就是通过运行pip install-U pyperclip来更新pyperclip。

另一个问题是,我从文件中获取字符串,但我不知道'在哪里,以及其他字符是否会引起问题……您需要提供有关如何从文件中检索字符串的更多详细信息。您的问题不清楚,但我想我知道可以复制你的问题。我只是相应地编辑了答案。我只是编辑了我的代码以使其更清晰,但你几乎复制了我的问题。除了切换到python 3,还有其他方法吗?因为我必须将整个python 2.7代码转换为python 3。@ProgramerBeginner我建议您升级到python 3。你迟早会的。Python安装的2to3工具部分在帮助您移植代码方面做得非常好。