【问题标题】:Python pyperclip cannot copy decodedPython pyperclip 无法复制解码
【发布时间】:2018-09-05 23:55:51
【问题描述】:

我刚刚发现,由于某种原因,使用 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 为我工作)。

【问题讨论】:

    标签: python string utf-8 decode pyperclip


    【解决方案1】:

    此问题已在 1.6.5 中修复,因此您只需运行 pip install -U pyperclip 更新 pyperclip。

    【讨论】:

      【解决方案2】:

      您似乎在使用非 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() 是一种黑客行为,不鼓励使用number of reasons

      【讨论】:

      • 另一个问题是我从文件中获取字符串,但我不知道 ' 在哪里以及其他字符是否会引起问题......
      • 您需要提供有关如何从文件中检索字符串的更多详细信息。
      • 您的问题不清楚,但我想我可以重现您的问题。我刚刚相应地编辑了答案。
      • 我只是编辑我的代码以使其更清晰,但您几乎复制了我的问题。除了切换到 python 3 之外还有其他方法吗,因为我必须将整个 python 2.7 代码转换为 python 3。
      • @ProgramerBeginner 我建议你还是升级到 Python 3。你迟早要这样做。 2to3 工具(Python 安装的一部分)在帮助您移植代码方面做得非常好。
      猜你喜欢
      • 2016-11-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      • 2019-01-10
      • 1970-01-01
      • 1970-01-01
      • 2018-03-08
      相关资源
      最近更新 更多