python 与系统剪贴板的交互

1,721 阅读1分钟

秉着浪费时间就是浪费生命的原则,先说结论:

使用 pyperclip

python 与系统剪贴板的交互

python下有两个库可以实现这个功能:pyperclipclipboard。两个库都是跨平台的剪贴板操作库,目前都可用(2022年4月10日)。

只不过,clipboard库年久失修,只提供了两个函数:copy()、paste()

image-20220403182219813

pyperclip 还有人维护,提供的函数也更为多样。

image-20220403182945128

使用示例

carbon

import pyperclip
pyperclip.copy('The text to be copied to the clipboard.')
text = pyperclip.paste()  # text will have the content of clipboard

import clipboard
clipboard.copy("abc")  # now the clipboard content will be string "abc"
text = clipboard.paste()  # text will have the content of clipboard

pyperclip其他常用函数

Pyperclip's documentation

pyperclip 的函数接口列表:

['copy', 'paste', 'waitForPaste', 'waitForNewPaste', 'set_clipboard', 'determine_clipboard']

pyperclip.waitForPaste(timeout=None)  # Doesn't return until non-empty text is on the clipboard.
pyperclip.waitForNewPaste(timeout=None)  # Doesn't return until the clipboard has something other than "original text".

使用过程中可能会遇到的问题: Pyperclip could not find a copy/paste mechanism for your system. \color{Red}{\text{Pyperclip could not find a copy/paste mechanism for your system. }}

解决方法\color{Green}{\text{解决方法}}

sudo apt-get install xsel to install the xsel utility.

sudo apt-get install xclip to install the xclip utility.

pip install gtk to install the gtk Python module.

pip install PyQt4 to install the PyQt4 Python module.

其他不常用函数:

# Explicitly sets the clipboard mechanism. The "clipboard mechanism" is how the copy() and paste() functions interact with the operating system to implement the copy/paste feature. The clipboard parameter must be one of:pbcopy、pbobjc (default on Mac OS X)、gtk、qt、xclip、xsel、klipper、windows (default on Windows)、no (this is what is set when no clipboard mechanism can be found)
pyperclip.set_clipboard(clipboard_mechanism)
# Determine the OS/platform and set the copy() and paste() functions accordingly.
pyperclip.determine_clipboard()