秉着浪费时间就是浪费生命的原则,先说结论:
使用 pyperclip 库
python 与系统剪贴板的交互
python下有两个库可以实现这个功能:pyperclip 和 clipboard。两个库都是跨平台的剪贴板操作库,目前都可用(2022年4月10日)。
只不过,clipboard库年久失修,只提供了两个函数:copy()、paste()
pyperclip 还有人维护,提供的函数也更为多样。
使用示例
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 的函数接口列表:
['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".
使用过程中可能会遇到的问题:
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()