用于将文本复制到剪贴板的独立于平台的工具
我正在尝试编写一个函数,将字符串参数复制到剪贴板。我打算在我一直在编写的 Python 脚本中使用它。这是我到目前为止所拥有的(在另一个堆栈溢出帖子上找到了大部分此片段):
from tkinter import Tk
def copy_to_clipboard(text):
text = str(text)
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append(text)
r.destroy()
我的问题是,当脚本停止时,复制的文本不再位于剪贴板上。
有没有可能的替代方案或解决办法?
对于我的问题,有一个好的独立于平台的解决方案吗?或者我是否必须检查用户使用的操作系统并从那里继续?
I am trying to write a function that copies a string parameter to the clipboard. I intend to use this in a Python script that I've been working on. This is what I have so far (found most this snippet on another stack overflow post):
from tkinter import Tk
def copy_to_clipboard(text):
text = str(text)
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append(text)
r.destroy()
My problem is that when the script stops, the copied text is no longer on the clipboard.
Is there any possible alternative or fix to this?
Is there a good platform independent solution to my problem? Or will I have to check for what OS the user is on and proceed from there?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,有一个适合您:)
使用 pyperclip。
Yes, there is one for you :)
Use pyperclip.
我想您正在运行带有 Gnome 的 Linux。
这是 Gnome 上的正常行为,一旦副本源消失,例如关闭从中复制的浏览器窗口,剪贴板数据也会被删除。解决方法是安装 gnome-clipboard-daemon ,它将像 Windows 和 KDE 一样保留剪贴板状态。
因此,在 Gnome 下运行时,除了让脚本保持运行之外,您无能为力。
I suppose that you're running on Linux with Gnome.
That's normal behavior on Gnome, as soon as the source of the copy vanishes e.g. closing the Browser Window you copied from, the clipboard data gets removed too. Workaround is to install the
gnome-clipboard-daemon
which will preserve the Clipboard state like Windows and KDE do.So, there's not much you can do when running under Gnome, besides leaving your script running.
这对我有用并且非常简单。 (仅限 Mac 测试)
http://www.macdrifter。 com/2011/12/python-and-the-mac-clipboard.html
This worked for me and is very simple. (mac tested only)
http://www.macdrifter.com/2011/12/python-and-the-mac-clipboard.html