Python pyperclip 无法复制解码
Python pyperclip cannot copy decoded
我刚刚发现,出于某种原因,当使用 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: only str, int, float, and bool values can be copied to the clipboard, not 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()
是一种 hack,不鼓励使用 number of reasons.
此问题已在 1.6.5 中修复,因此您只需按 运行 pip install -U pyperclip
.
更新 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(string.decode('utf-8'))
它会引发这个错误:PyperclipException: only str, int, float, and bool values can be copied to the clipboard, not 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()
是一种 hack,不鼓励使用 number of reasons.
此问题已在 1.6.5 中修复,因此您只需按 运行 pip install -U pyperclip
.