You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.10无需外部库实现文本复制到剪贴板的方法

无需外部库实现Python 3.10写入剪贴板

以下是分平台的实现方案,均无需安装Python外部库:

Windows平台(纯标准库)

利用Python标准库ctypes调用Windows系统API实现剪贴板写入:

import ctypes
from ctypes import wintypes

CF_UNICODETEXT = 13

# 加载系统库并定义函数参数/返回值类型
user32 = ctypes.WinDLL('user32', use_last_error=True)
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)

user32.OpenClipboard.argtypes = [wintypes.HWND]
user32.OpenClipboard.restype = wintypes.BOOL
user32.EmptyClipboard.restype = wintypes.BOOL
user32.SetClipboardData.argtypes = [wintypes.UINT, wintypes.HANDLE]
user32.SetClipboardData.restype = wintypes.HANDLE
user32.CloseClipboard.restype = wintypes.BOOL
kernel32.GlobalAlloc.argtypes = [wintypes.UINT, ctypes.c_size_t]
kernel32.GlobalAlloc.restype = wintypes.HGLOBAL
kernel32.GlobalLock.argtypes = [wintypes.HGLOBAL]
kernel32.GlobalLock.restype = ctypes.c_void_p
kernel32.GlobalUnlock.argtypes = [wintypes.HGLOBAL]
kernel32.GlobalUnlock.restype = wintypes.BOOL

def set_clipboard_text(text):
    text_bytes = text.encode('utf-16le')
    # 分配可移动全局内存
    h_global = kernel32.GlobalAlloc(0x0040, len(text_bytes) + 2)
    if not h_global:
        raise ctypes.WinError(ctypes.get_last_error())
    try:
        lp_global = kernel32.GlobalLock(h_global)
        if not lp_global:
            raise ctypes.WinError(ctypes.get_last_error())
        ctypes.memmove(lp_global, text_bytes, len(text_bytes))
        kernel32.GlobalUnlock(h_global)
        
        if not user32.OpenClipboard(None):
            raise ctypes.WinError(ctypes.get_last_error())
        try:
            user32.EmptyClipboard()
            if user32.SetClipboardData(CF_UNICODETEXT, h_global) is None:
                raise ctypes.WinError(ctypes.get_last_error())
        finally:
            user32.CloseClipboard()
    except:
        kernel32.GlobalFree(h_global)
        raise

# 调用示例
set_clipboard_text("Hello, Windows剪贴板!")

macOS平台(依赖系统自带命令)

macOS自带pbcopy命令,通过标准库subprocess调用实现写入:

import subprocess

def set_clipboard_text(text):
    subprocess.run(['pbcopy'], input=text.encode('utf-8'), check=True)

# 调用示例
set_clipboard_text("Hello, macOS剪贴板!")

Linux平台(依赖系统工具)

需先通过系统包管理器安装xclip或xsel(如sudo apt install xclip),再通过subprocess调用:

基于xclip实现:

import subprocess

def set_clipboard_text(text):
    subprocess.run(
        ['xclip', '-selection', 'clipboard'],
        input=text.encode('utf-8'),
        check=True
    )

# 调用示例
set_clipboard_text("Hello, Linux剪贴板!")

基于xsel实现:

import subprocess

def set_clipboard_text(text):
    subprocess.run(
        ['xsel', '-ib'],
        input=text.encode('utf-8'),
        check=True
    )

# 调用示例
set_clipboard_text("Hello, Linux剪贴板!")

内容的提问来源于stack exchange,提问作者fullwoodenshovel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 07:35:18