我试图使一个基本的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
其他回答
你也可以使用>剪贴板
import clipboard
def copy(txt):
clipboard.copy(txt)
copy("your txt")
如果(仅当)应用程序已经使用了Qt,您可以使用这个(优点是没有额外的第三方依赖)
from PyQt5.QtWidgets import QApplication
clipboard = QApplication.clipboard()
# get text (if there's text inside instead of e.g. file)
clipboard.text()
# set text
clipboard.setText(s)
这要求已经构造了Qt应用程序对象,因此除非应用程序已经使用了Qt,否则不应该使用它。
此外,通常情况下,在X系统(可能还有其他系统)中,除非使用parcellite或xclipboard之类的东西,否则内容只会持续到应用程序存在为止。
文档:
QGuiApplication Class | Qt GUI 5.15.6 QClipboard Class | Qt GUI 5.15.6
请参见:python - PyQT -复制文件到剪贴板-堆栈溢出
你可以使用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/
看起来您需要将win32clipboard添加到站点包中。它是pywin32包的一部分
我在这里分享的代码片段利用了格式化文本文件的功能:如果您想将复杂的输出复制到剪贴板,该怎么办?(比如一个列中的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
推荐文章
- 类中的Python装饰器
- Git与Mercurial仓库的互操作性
- 在Python中锁定文件
- 得到熊猫栏目的总数
- 从pandas DataFrame中删除名称包含特定字符串的列
- 如何从命令行在windows中找到mysql数据目录
- Mock vs MagicMock
- 如何阅读一个。xlsx文件使用熊猫库在iPython?
- 如何访问熊猫组由数据帧按键
- Pandas和NumPy+SciPy在Python中的区别是什么?
- 将列表转换为集合会改变元素的顺序
- 如何在matplotlib更新一个情节
- TypeError: ` NoneType `对象在Python中不可迭代
- 如何在Vim注释掉一个Python代码块
- python标准库中的装饰符(特别是@deprecated)