Platform independent tool to copy text to clipboard

邮差的信 提交于 2019-12-03 16:07:15

问题


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?


回答1:


Yes, there is one for you :)

Use pyperclip.




回答2:


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.




回答3:


This worked for me and is very simple. (mac tested only)

http://www.macdrifter.com/2011/12/python-and-the-mac-clipboard.html



来源:https://stackoverflow.com/questions/4308152/platform-independent-tool-to-copy-text-to-clipboard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!