我试图使一个基本的Windows应用程序构建出用户输入的字符串,然后将其添加到剪贴板。如何使用Python将字符串复制到剪贴板?
当前回答
使用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安装(即我目前使用的自定义构建)。
其他回答
看起来您需要将win32clipboard添加到站点包中。它是pywin32包的一部分
你也可以使用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()
你也可以使用>剪贴板
import clipboard
def copy(txt):
clipboard.copy(txt)
copy("your txt")
最简单的方法是用pyperclip。适用于python 2和3。
要安装这个库,请使用:
pip install pyperclip
使用示例:
import pyperclip
pyperclip.copy("your string")
如果你想获取剪贴板的内容:
clipboard_content = pyperclip.paste()
我在这里分享的代码片段利用了格式化文本文件的功能:如果您想将复杂的输出复制到剪贴板,该怎么办?(比如一个列中的numpy数组或一个列表)
import subprocess
import os
def cp2clip(clist):
#create a temporary file
fi=open("thisTextfileShouldNotExist.txt","w")
#write in the text file the way you want your data to be
for m in clist:
fi.write(m+"\n")
#close the file
fi.close()
#send "clip < file" to the shell
cmd="clip < thisTextfileShouldNotExist.txt"
w = subprocess.check_call(cmd,shell=True)
#delete the temporary text file
os.remove("thisTextfileShouldNotExist.txt")
return w
只适用于windows,我猜可以适用于linux或mac。可能有点复杂……
例子:
>>>cp2clip(["ET","phone","home"])
>>>0
在任何文本编辑器中按Ctrl+V:
ET
phone
home