pip install pyperclip
当显示Successfully installed pyperclip
时,说明安装成功了
可以在Python IDE
中输入这行内容测试:
import pyperclip
我们先来看第一个,复制内容
import pyperclip as pc
pc.copy("Hello")
可以看到,剪贴板里多出了内容Hello
当然,也可以这么写
import pyperclip
pyperclip.copy("Hello")
import pyperclip as pc
text = "Hello,world"
pc.copy(text)
import pyperclip as pc
pc.copy("I love Programming")
pc.paste()
Pyperclip
A cross-platform clipboard module for Python, with copy & paste functions for plain text.
By Al Sweigart al@inventwithpython.com
BSD License
Usage:
import pyperclip
pyperclip.copy('The text to be copied to the clipboard.')
spam = pyperclip.paste()
if not pyperclip.is_available():
print("Copy functionality unavailable!")
On Windows, no additional modules are needed.
On Mac, the pyobjc module is used, falling back to the pbcopy and pbpaste cli
commands. (These commands should come with OS X.).
On Linux, install xclip or xsel via package manager. For example, in Debian:
sudo apt-get install xclip
sudo apt-get install xsel
Otherwise on Linux, you will need the gtk or PyQt5/PyQt4 modules installed.
gtk and PyQt4 modules are not available for Python 3,
and this module does not work with PyGObject yet.
Note: There seems to be a way to get gtk on Python 3, according to:
https://askubuntu.com/questions/697397/python3-is-not-supporting-gtk-module
Cygwin is currently not supported.
Security Note: This module runs programs with these names:
- which
- where
- pbcopy
- pbpaste
- xclip
- xsel
- klipper
- qdbus
A malicious user could rename or add programs with these names, tricking
Pyperclip into running them with whatever permissions the Python process has.
__version__ = '1.7.0'
import contextlib
import ctypes
import os
import platform
import subprocess
import sys
import time
import warnings
from ctypes import c_size_t, sizeof, c_wchar_p, get_errno, c_wchar
HAS_DISPLAY = os.getenv("DISPLAY", False)
EXCEPT_MSG = """
Pyperclip could not find a copy/paste mechanism for your system.
For more information, please visit https://pyperclip.readthedocs.io/en/latest/introduction.html#not-implemented-error """
PY2 = sys.version_info[0] == 2
STR_OR_UNICODE = unicode if PY2 else str
ENCODING = 'utf-8'
if platform.system() == 'Windows':
WHICH_CMD = 'where'
else:
WHICH_CMD = 'which'
def _executable_exists(name):
return subprocess.call([WHICH_CMD, name],
stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0
class PyperclipException(RuntimeError):
class PyperclipWindowsException(PyperclipException):
def __init__(self, message):
message += " (%s)" % ctypes.WinError()
super(PyperclipWindowsException, self).__init__(message)
def _stringifyText(text):
if PY2:
acceptedTypes = (unicode, str, int, float, bool)
else:
acceptedTypes = (str, int, float, bool)
if not isinstance(text, acceptedTypes):
raise PyperclipException('only str, int, float, and bool values can be copied to the clipboard, not %s' % (text.__class__.__name__))
return STR_OR_UNICODE(text)
def init_osx_pbcopy_clipboard():
def copy_osx_pbcopy(text):
text = _stringifyText(text)
p = subprocess.Popen(['pbcopy', 'w'],
stdin=subprocess.PIPE, close_fds=True)
p.communicate(input=text.encode(ENCODING))
def paste_osx_pbcopy():
p = subprocess.Popen(['pbpaste', 'r'],
stdout=subprocess.PIPE, close_fds=True)
stdout, stderr = p.communicate()
return stdout.decode(ENCODING)
return copy_osx_pbcopy, paste_osx_pbcopy
def init_osx_pyobjc_clipboard():
def copy_osx_pyobjc(text):
'''Copy string argument to clipboard'''
text = _stringifyText(text)
newStr = Foundation.NSString.stringWithString_(text).nsstring()
newData = newStr.dataUsingEncoding_(Foundation.NSUTF8StringEncoding)
board = AppKit.NSPasteboard.generalPasteboard()
board.declareTypes_owner_([AppKit.NSStringPboardType], None)
board.setData_forType_(newData, AppKit.NSStringPboardType)
def paste_osx_pyobjc():
"Returns contents of clipboard"
board = AppKit.NSPasteboard.generalPasteboard()
content = board.stringForType_(AppKit.NSStringPboardType)
return content
return copy_osx_pyobjc, paste_osx_pyobjc
def init_gtk_clipboard():
global gtk
import gtk
def copy_gtk(text):
global cb
text = _stringifyText(text)
cb = gtk.Clipboard()
cb.set_text(text)
cb.store()
def paste_gtk():
clipboardContents = gtk.Clipboard().wait_for_text()
if clipboardContents is None:
return ''
else:
return clipboardContents
return copy_gtk, paste_gtk
def init_qt_clipboard():
global QApplication
try:
from qtpy.QtWidgets import QApplication
except:
try:
from PyQt5.QtWidgets import QApplication
except:
from PyQt4.QtGui import QApplication
app = QApplication.instance()
if app is None:
app = QApplication([])
def copy_qt(text):
text = _stringifyText(text)
cb = app.clipboard()
cb.setText(text)
def paste_qt():
cb = app.clipboard()
return STR_OR_UNICODE(cb.text())
return copy_qt, paste_qt
def init_xclip_clipboard():
DEFAULT_SELECTION='c'
PRIMARY_SELECTION='p'
def copy_xclip(text, primary=False):
text = _stringifyText(text)
selection=DEFAULT_SELECTION
if primary:
selection=PRIMARY_SELECTION
p = subprocess.Popen(['xclip', '-selection', selection],
stdin=subprocess.PIPE, close_fds=True)
p.communicate(input=text.encode(ENCODING))
def paste_xclip(primary=False):
selection=DEFAULT_SELECTION
if primary:
selection=PRIMARY_SELECTION
p = subprocess.Popen(['xclip', '-selection', selection, '-o'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True)
stdout, stderr = p.communicate()
return stdout.decode(ENCODING)
return copy_xclip, paste_xclip
def init_xsel_clipboard():
DEFAULT_SELECTION='-b'
PRIMARY_SELECTION='-p'
def copy_xsel(text, primary=False):
text = _stringifyText(text)
selection_flag = DEFAULT_SELECTION
if primary:
selection_flag = PRIMARY_SELECTION
p = subprocess.Popen(['xsel', selection_flag, '-i'],
stdin=subprocess.PIPE, close_fds=True)
p.communicate(input=text.encode(ENCODING))
def paste_xsel(primary=False):
selection_flag = DEFAULT_SELECTION
if primary:
selection_flag = PRIMARY_SELECTION
p = subprocess.Popen(['xsel', selection_flag, '-o'],
stdout=subprocess.PIPE, close_fds=True)
stdout, stderr = p.communicate()
return stdout.decode(ENCODING)
return copy_xsel, paste_xsel
def init_klipper_clipboard():
def copy_klipper(text):
text = _stringifyText(text)
p = subprocess.Popen(
['qdbus', 'org.kde.klipper', '/klipper', 'setClipboardContents',
text.encode(ENCODING)],
stdin=subprocess.PIPE, close_fds=True)
p.communicate(input=None)
def paste_klipper():
p = subprocess.Popen(
['qdbus', 'org.kde.klipper', '/klipper', 'getClipboardContents'],
stdout=subprocess.PIPE, close_fds=True)
stdout, stderr = p.communicate()
clipboardContents = stdout.decode(ENCODING)
assert len(clipboardContents) > 0
assert clipboardContents.endswith('\n')
if clipboardContents.endswith('\n'):
clipboardContents = clipboardContents[:-1]
return clipboardContents
return copy_klipper, paste_klipper
def init_dev_clipboard_clipboard():
def copy_dev_clipboard(text):
text = _stringifyText(text)
if text == '':
warnings.warn('Pyperclip cannot copy a blank string to the clipboard on Cygwin. This is effectively a no-op.')
if '\r' in text:
warnings.warn('Pyperclip cannot handle \\r characters on Cygwin.')
fo = open('/dev/clipboard', 'wt')
fo.write(text)
fo.close()
def paste_dev_clipboard():
fo = open('/dev/clipboard', 'rt')
content = fo.read()
fo.close()
return content
return copy_dev_clipboard, paste_dev_clipboard
def init_no_clipboard():
class ClipboardUnavailable(object):
def __call__(self, *args, **kwargs):
raise PyperclipException(EXCEPT_MSG)
if PY2:
def __nonzero__(self):
return False
else:
def __bool__(self):
return False
return ClipboardUnavailable(), ClipboardUnavailable()
class CheckedCall(object):
def __init__(self, f):
super(CheckedCall, self).__setattr__("f", f)
def __call__(self, *args):
ret = self.f(*args)
if not ret and get_errno():
raise PyperclipWindowsException("Error calling " + self.f.__name__)
return ret
def __setattr__(self, key, value):
setattr(self.f, key, value)
def init_windows_clipboard():
global HGLOBAL, LPVOID, DWORD, LPCSTR, INT, HWND, HINSTANCE, HMENU, BOOL, UINT, HANDLE
from ctypes.wintypes import (HGLOBAL, LPVOID, DWORD, LPCSTR, INT, HWND,
HINSTANCE, HMENU, BOOL, UINT, HANDLE)
windll = ctypes.windll
msvcrt = ctypes.CDLL('msvcrt')
safeCreateWindowExA = CheckedCall(windll.user32.CreateWindowExA)
safeCreateWindowExA.argtypes = [DWORD, LPCSTR, LPCSTR, DWORD, INT, INT,
INT, INT, HWND, HMENU, HINSTANCE, LPVOID]
safeCreateWindowExA.restype = HWND
safeDestroyWindow = CheckedCall(windll.user32.DestroyWindow)
safeDestroyWindow.argtypes = [HWND]
safeDestroyWindow.restype = BOOL
OpenClipboard = windll.user32.OpenClipboard
OpenClipboard.argtypes = [HWND]
OpenClipboard.restype = BOOL
safeCloseClipboard = CheckedCall(windll.user32.CloseClipboard)
safeCloseClipboard.argtypes = []
safeCloseClipboard.restype = BOOL
safeEmptyClipboard = CheckedCall(windll.user32.EmptyClipboard)
safeEmptyClipboard.argtypes = []
safeEmptyClipboard.restype = BOOL
safeGetClipboardData = CheckedCall(windll.user32.GetClipboardData)
safeGetClipboardData.argtypes = [UINT]
safeGetClipboardData.restype = HANDLE
safeSetClipboardData = CheckedCall(windll.user32.SetClipboardData)
safeSetClipboardData.argtypes = [UINT, HANDLE]
safeSetClipboardData.restype = HANDLE
safeGlobalAlloc = CheckedCall(windll.kernel32.GlobalAlloc)
safeGlobalAlloc.argtypes = [UINT, c_size_t]
safeGlobalAlloc.restype = HGLOBAL
safeGlobalLock = CheckedCall(windll.kernel32.GlobalLock)
safeGlobalLock.argtypes = [HGLOBAL]
safeGlobalLock.restype = LPVOID
safeGlobalUnlock = CheckedCall(windll.kernel32.GlobalUnlock)
safeGlobalUnlock.argtypes = [HGLOBAL]
safeGlobalUnlock.restype = BOOL
wcslen = CheckedCall(msvcrt.wcslen)
wcslen.argtypes = [c_wchar_p]
wcslen.restype = UINT
GMEM_MOVEABLE = 0x0002
CF_UNICODETEXT = 13
@contextlib.contextmanager
def window():
Context that provides a valid Windows hwnd.
hwnd = safeCreateWindowExA(0, b"STATIC", None, 0, 0, 0, 0, 0,
None, None, None, None)
try:
yield hwnd
finally:
safeDestroyWindow(hwnd)
@contextlib.contextmanager
def clipboard(hwnd):
Context manager that opens the clipboard and prevents
other applications from modifying the clipboard content.
t = time.time() + 0.5
success = False
while time.time() < t:
success = OpenClipboard(hwnd)
if success:
break
time.sleep(0.01)
if not success:
raise PyperclipWindowsException("Error calling OpenClipboard")
try:
yield
finally:
safeCloseClipboard()
def copy_windows(text):
text = _stringifyText(text)
with window() as hwnd:
with clipboard(hwnd):
safeEmptyClipboard()
if text:
count = wcslen(text) + 1
handle = safeGlobalAlloc(GMEM_MOVEABLE,
count * sizeof(c_wchar))
locked_handle = safeGlobalLock(handle)
ctypes.memmove(c_wchar_p(locked_handle), c_wchar_p(text), count * sizeof(c_wchar))
safeGlobalUnlock(handle)
safeSetClipboardData(CF_UNICODETEXT, handle)
def paste_windows():
with clipboard(None):
handle = safeGetClipboardData(CF_UNICODETEXT)
if not handle:
return ""
return c_wchar_p(handle).value
return copy_windows, paste_windows
def init_wsl_clipboard():
def copy_wsl(text):
text = _stringifyText(text)
p = subprocess.Popen(['clip.exe'],
stdin=subprocess.PIPE, close_fds=True)
p.communicate(input=text.encode(ENCODING))
def paste_wsl():
p = subprocess.Popen(['powershell.exe', '-command', 'Get-Clipboard'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
close_fds=True)
stdout, stderr = p.communicate()
return stdout[:-2].decode(ENCODING)
return copy_wsl, paste_wsl
def determine_clipboard():
Determine the OS/platform and set the copy() and paste() functions
accordingly.
global Foundation, AppKit, gtk, qtpy, PyQt4, PyQt5
if 'cygwin' in platform.system().lower():
if os.path.exists('/dev/clipboard'):
warnings.warn('Pyperclip\'s support for Cygwin is not perfect, see https://github.com/asweigart/pyperclip/issues/55')
return init_dev_clipboard_clipboard()
elif os.name == 'nt' or platform.system() == 'Windows':
return init_windows_clipboard()
if platform.system() == 'Linux':
with open('/proc/version', 'r') as f:
if "Microsoft" in f.read():
return init_wsl_clipboard()
if os.name == 'mac' or platform.system() == 'Darwin':
try:
import Foundation
import AppKit
except ImportError:
return init_osx_pbcopy_clipboard()
else:
return init_osx_pyobjc_clipboard()
if HAS_DISPLAY:
try:
import gtk
except ImportError:
pass
else:
return init_gtk_clipboard()
if _executable_exists("xsel"):
return init_xsel_clipboard()
if _executable_exists("xclip"):
return init_xclip_clipboard()
if _executable_exists("klipper") and _executable_exists("qdbus"):
return init_klipper_clipboard()
try:
import qtpy
except ImportError:
try:
import PyQt5
except ImportError:
try:
import PyQt4
except ImportError:
pass
else:
return init_qt_clipboard()
else:
return init_qt_clipboard()
else:
return init_qt_clipboard()
return init_no_clipboard()
def set_clipboard(clipboard):
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
- xclip
- xsel
- klipper
- windows (default on Windows)
- no (this is what is set when no clipboard mechanism can be found)
global copy, paste
clipboard_types = {'pbcopy': init_osx_pbcopy_clipboard,
'pyobjc': init_osx_pyobjc_clipboard,
'gtk': init_gtk_clipboard,
'qt': init_qt_clipboard,
'xclip': init_xclip_clipboard,
'xsel': init_xsel_clipboard,
'klipper': init_klipper_clipboard,
'windows': init_windows_clipboard,
'no': init_no_clipboard}
if clipboard not in clipboard_types:
raise ValueError('Argument must be one of %s' % (', '.join([repr(_) for _ in clipboard_types.keys()])))
copy, paste = clipboard_types[clipboard]()
def lazy_load_stub_copy(text):
A stub function for copy(), which will load the real copy() function when
called so that the real copy() function is used for later calls.
This allows users to import pyperclip without having determine_clipboard()
automatically run, which will automatically select a clipboard mechanism.
This could be a problem if it selects, say, the memory-heavy PyQt4 module
but the user was just going to immediately call set_clipboard() to use a
different clipboard mechanism.
The lazy loading this stub function implements gives the user a chance to
call set_clipboard() to pick another clipboard mechanism. Or, if the user
simply calls copy() or paste() without calling set_clipboard() first,
will fall back on whatever clipboard mechanism that determine_clipboard()
automatically chooses.
global copy, paste
copy, paste = determine_clipboard()
return copy(text)
def lazy_load_stub_paste():
A stub function for paste(), which will load the real paste() function when
called so that the real paste() function is used for later calls.
This allows users to import pyperclip without having determine_clipboard()
automatically run, which will automatically select a clipboard mechanism.
This could be a problem if it selects, say, the memory-heavy PyQt4 module
but the user was just going to immediately call set_clipboard() to use a
different clipboard mechanism.
The lazy loading this stub function implements gives the user a chance to
call set_clipboard() to pick another clipboard mechanism. Or, if the user
simply calls copy() or paste() without calling set_clipboard() first,
will fall back on whatever clipboard mechanism that determine_clipboard()
automatically chooses.
global copy, paste
copy, paste = determine_clipboard()
return paste()
def is_available():
return copy != lazy_load_stub_copy and paste != lazy_load_stub_paste
copy, paste = lazy_load_stub_copy, lazy_load_stub_paste
__all__ = ['copy', 'paste', 'set_clipboard', 'determine_clipboard']
在这个信息化快速发展的时代,高效的信息处理变得尤为关键。Python,作为一门强大的编程语言,其灵活性以及多样的库函数,使其成为处理信息不可或缺的利器。在此背景下,我决定分享我对其中两个实用Python库——Pyperclip和CnOCR的理解和使用,以帮助大家在日常工作和学习中提高效率。
首先,我们将会详细探讨Pyperclip,这是一个简洁高效的跨平台剪贴板库,让我们可以轻松地在Python代码和系统剪贴板之间传输文本数据。随后,我们将介绍OCR技术及其在Python中的应用,尤其是CnOCR库的强大功
pandas 里面有一个 pd.read_clipboard 函数,可以根据你复制的内容生成DataFrame。是的,就是我们平时选中,然后 Ctrl+C 时拷贝的内容。所以比较神奇,那么 pandas 到底是怎么做到的,它是怎么读出我们使用 Ctrl +C 复制的内容呢。看了一下源码,不同的操作系统使用的复制方式不同,Windows 比较复杂,方法是使用了ctypes,然后调用了操作系统的一个动态库实现的;而 macOS 和 Linux 比较简单,调用的是内置的命令。
Pyperclip - Python 的剪贴板实用程序库
Pyperclip 是一个用于跨平台复制和粘贴的简单 Python 库。它允许您在不同的操作系统(如 Windows、macOS 和 Linux)之间轻松地将文本从一个应用程序复制到另一个应用程序。
Pyperclip 能用来做什么?
Pyperclip 可以方便地处理文本的复制和粘贴操作,在以下场景中特别有用:
在脚本或自动化任务中实现...
在完成《Python程序设计》的实验时,用到了一个新模块pyperclip。这个模块是第一次见,也是第一次用,查阅相关资料后,感觉这个模块有点意思。
一、pyperclip的安装
pyperclip模块为第三方模块,需安装后使用。
pyperclip模块的安装与python其他模块的安装异曲同工。
WIN+R打开cmd,
首先检查pip命令是否已经升级到最新版本
pip命令已经升级到最新版本...
用 pyperclip 模块拷贝粘贴字符串pyperclip 模块有 copy()和 paste()函数, 可以向计算机的剪贴板发送文本, 或从它接收文本。将程序的输出发送到剪贴板, 使它很容易粘贴到邮件、文字处理程序或其他软件中。 pyperclip 模块不是 Python 自带的。要安装它, 请遵从附录 A 中安装第三方模块的指南。安装 pyperclip 模块后, 在交互式环境中输入以下代码...
通过本文的介绍,我们了解了PyAutoGUI和Pyperclip这两个强大的Python库,并学会了它们的基本使用方法。这两个库的应用远不止于本文所涉及的内容,读者可以根据实际需求深入学习,进一步探索它们的更多功能和应用场景。相信通过不断学习和实践,我们能够更好地利用自动化操作提升工作和学习的效率,实现更多惊人的功能与创意。让我们一起打造高效自动化操作的未来吧!
python读取剪切板有两个模块:win32clipboard和pyperclip,都需要安装,前者是pywin32的一部分,直接安装pywin32即可,后者可以在cmd里直接pip安装。
安装pyperclip:
大概等一两分钟就好了~~~
不过我不知道怎么选安装目录,我发现我的被安装在了这个目录里:d:\anaconda\anzhuang\lib\site-packages (1.7...