我试图使一个基本的Windows应用程序构建出用户输入的字符串,然后将其添加到剪贴板。如何使用Python将字符串复制到剪贴板?


当前回答

你也可以使用ctypes来进入Windows API,避免大量的pywin32包。这是我使用的方法(请原谅我的风格不好,但我的想法是这样的):

import ctypes

# Get required functions, strcpy..
strcpy = ctypes.cdll.msvcrt.strcpy
ocb = ctypes.windll.user32.OpenClipboard    # Basic clipboard functions
ecb = ctypes.windll.user32.EmptyClipboard
gcd = ctypes.windll.user32.GetClipboardData
scd = ctypes.windll.user32.SetClipboardData
ccb = ctypes.windll.user32.CloseClipboard
ga = ctypes.windll.kernel32.GlobalAlloc    # Global memory allocation
gl = ctypes.windll.kernel32.GlobalLock     # Global memory Locking
gul = ctypes.windll.kernel32.GlobalUnlock
GMEM_DDESHARE = 0x2000

def Get():
  ocb(None) # Open Clip, Default task

  pcontents = gcd(1) # 1 means CF_TEXT.. too lazy to get the token thingy...

  data = ctypes.c_char_p(pcontents).value

  #gul(pcontents) ?
  ccb()

  return data

def Paste(data):
  ocb(None) # Open Clip, Default task

  ecb()

  hCd = ga(GMEM_DDESHARE, len(bytes(data,"ascii")) + 1)

  pchData = gl(hCd)

  strcpy(ctypes.c_char_p(pchData), bytes(data, "ascii"))

  gul(hCd)

  scd(1, hCd)

  ccb()

其他回答

你可以试试这个:

command = 'echo content |clip'
subprocess.check_call(command, shell=True)

使用stdlib解决方案,没有安全问题

下面的解决方案在Linux中工作,不需要任何额外的库,也没有在shell中执行不需要的代码的风险。

import subprocess

def to_clipboard(text: str) -> None:
    sp = subprocess.Popen(["xclip"], stdin=subprocess.PIPE, 
                                      stdout=subprocess.PIPE)
    sp.communicate(text.encode("utf8"))

注意,在Linux中有多个剪贴板,你用中鼠标(主)和另一个你用按STRG+C,STRG+V。

您可以通过添加一个选择参数来定义使用哪个剪贴板,即["xclip", "-selection", "clipboard"]。 详见man xclip。

如果您使用Windows,只需将xclip替换为clip。

这个解决方案不需要Tkinter,它没有一些Python安装(即我目前使用的自定义构建)。

这是我发现的最简单可靠的方法,如果你可以依赖熊猫。然而,我不认为这是熊猫API的官方部分,所以它可能会打破未来的更新。它的工作为0.25.3

from pandas.io import clipboard
clipboard.copy("test")

看起来您需要将win32clipboard添加到站点包中。它是pywin32包的一部分

我的多平台解决方案基于这个问题:

import subprocess
import distutils.spawn

def clipit(text):
    if distutils.spawn.find_executable("xclip"):
        # for Linux
        subprocess.run(["xclip", "-i"], input=text.encode("utf8"))
    elif distutils.spawn.find_executable("xsel"):
        # for Linux
        subprocess.run(["xsel", "--input"], input=text.encode("utf8"))
    elif distutils.spawn.find_executable("clip"):
        # for Windows
        subprocess.run(["clip"], input=text.encode("utf8"))
    else:
        import pyperclip

        print("I use module pyperclip.")
        pyperclip.copy(text)