我试图使一个基本的Windows应用程序构建出用户输入的字符串,然后将其添加到剪贴板。如何使用Python将字符串复制到剪贴板?
当前回答
我在这里分享的代码片段利用了格式化文本文件的功能:如果您想将复杂的输出复制到剪贴板,该怎么办?(比如一个列中的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
其他回答
复制剪贴板的代码片段:
在名为(clipboard.py)的模块中创建包装器Python代码:
import clr
clr.AddReference('System.Windows.Forms')
from System.Windows.Forms import Clipboard
def setText(text):
Clipboard.SetText(text)
def getText():
return Clipboard.GetText()
然后将上述模块导入到代码中。
import io
import clipboard
code = clipboard.getText()
print code
code = "abcd"
clipboard.setText(code)
我必须赞扬博客文章在IronPython剪贴板访问。
实际上,对于这个简单的任务,pywin32和ctypes似乎是多余的。tkinter是一个跨平台的GUI框架,默认情况下与Python一起发布,并具有剪贴板访问方法和其他很酷的东西。
如果你所需要的只是将一些文本放入系统剪贴板,这将做到:
from tkinter import Tk # in Python 2, use "Tkinter" instead
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('i can has clipboardz?')
r.update() # now it stays on the clipboard after the window is closed
r.destroy()
仅此而已,不需要在特定于平台的第三方库上浪费时间。
如果您正在使用Python 2,请将tkinter替换为tkinter。
你可以使用winclip32模块! 安装:
pip install winclip32
复制:
import winclip32
winclip32.set_clipboard_data(winclip32.UNICODE_STD_TEXT, "some text")
得到:
import winclip32
print(winclip32.get_clipboard_data(winclip32.UNICODE_STD_TEXT))
欲了解更多信息:https://pypi.org/project/winclip32/
使用python的剪贴板库!
import clipboard as cp
cp.copy("abc")
剪贴板现在包含'abc'。粘贴快乐!
使用pyperclip模块
使用pip安装pyperclip。
https://pypi.org/project/pyperclip/
复制文本“Hello World!”到剪贴板
import pyperclip
pyperclip.copy('Hello World!')
你可以在任何地方使用Ctrl+V来粘贴它。
使用python粘贴复制的文本
pyperclip.paste() # This returns the copied text of type <class 'str'>
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 我如何找到哪个程序正在使用端口80在Windows?
- 使用try和。Python中的if