用于将文本复制到剪贴板的Python脚本[重复]

时间:2022-02-21 16:21:45

This question already has an answer here:

这个问题在这里已有答案:

I just need a python script that copies text to the clipboard.

我只需要一个将文本复制到剪贴板的python脚本。

After the script gets executed i need the output of the text to be pasted to another source. Is it possible to write a python script that does this job?

脚本执行后,我需要将文本的输出粘贴到另一个源。是否有可能编写一个执行此工作的python脚本?

12 个解决方案

#1


77  

See Pyperclip. Example (taken from Pyperclip site):

见Pyperclip。示例(取自Pyperclip站点):

import pyperclip
pyperclip.copy('The text to be copied to the clipboard.')
spam = pyperclip.paste()

Also, see Xerox. But it appears to have more dependencies.

另外,请参阅Xerox。但它似乎有更多的依赖。

#2


30  

On mac i use this function.

在Mac上我使用此功能。

import os 
data = "hello world"
os.system("echo '%s' | pbcopy" % data)

It will copy "hello world" to the clipboard.

它会将“hello world”复制到剪贴板。

#3


26  

Use Tkinter:

使用Tkinter:

https://*.com/a/4203897/2804197

https://*.com/a/4203897/2804197

try:
    from Tkinter import Tk
except ImportError:
    from tkinter import Tk
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()

(Original author: https://*.com/users/449571/atomizer)

(原作者:https://*.com/users/449571/atomizer)

#4


11  

Pyperclip seems to be up to the task.

Pyperclip似乎可以胜任这项任务。

#5


7  

To use native Python directories, use:

要使用本机Python目录,请使用:

import subprocess

def copy2clip(txt):
    cmd='echo '+txt.strip()+'|clip'
    return subprocess.check_call(cmd, shell=True)

Then use:

然后使用:

copy2clip('This is on my clipboard!')

to call the function.

调用该函数。

#6


4  

This is the only way that worked for me using Python 3.5.2 plus it's the easiest to implement w/ using the standard PyData suite

这是使用Python 3.5.2的唯一方法,使用标准PyData套件最容易实现

Shout out to https://*.com/users/4502363/gadi-oron for the answer (I copied it completely) from How do I copy a string to the clipboard on Windows using Python?

请大声向https://*.com/users/4502363/gadi-oron寻求答案(我完全复制了),如何使用Python将字符串复制到Windows上的剪贴板?

import pandas as pd
df=pd.DataFrame(['Text to copy'])
df.to_clipboard(index=False,header=False)

I wrote a little wrapper for it that I put in my ipython profile <3

我为它写了一个小包装器,我把它放在我的ipython配置文件中<3

#7


3  

GTK3:

GTK3:

#!/usr/bin/python3

from gi.repository import Gtk, Gdk


class Hello(Gtk.Window):

    def __init__(self):
        super(Hello, self).__init__()
        clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
        clipboard.set_text("hello world", -1)
        Gtk.main_quit()


def main():
    Hello()
    Gtk.main()

if __name__ == "__main__":
    main()

#8


3  

I try this clipboard 0.0.4 and it works well.

我尝试这个剪贴板0.0.4,它运作良好。

https://pypi.python.org/pypi/clipboard/0.0.4

https://pypi.python.org/pypi/clipboard/0.0.4

import clipboard
clipboard.copy("abc")  # now the clipboard content will be string "abc"
text = clipboard.paste()  # text will have the content of clipboard

#9


2  

One more answer to improve on: https://*.com/a/4203897/2804197 and https://*.com/a/25476462/1338797 (Tkinter).

还有一个改进的答案:https://*.com/a/4203897/2804197和https://*.com/a/25476462/1338797(Tkinter)。

Tkinter is nice, because it's either included with Python (Windows) or easy to install (Linux), and thus requires little dependencies for the end user.

Tkinter很好,因为它包含在Python(Windows)或易于安装(Linux)中,因此对最终用户几乎没有依赖性。

Here I have a "full-blown" example, which copies the arguments or the standard input, to clipboard, and - when not on Windows - waits for the user to close the application:

在这里,我有一个“完整的”示例,它将参数或标准输入复制到剪贴板,并且 - 当不在Windows上时 - 等待用户关闭应用程序:

import sys

try:
    from Tkinter import Tk
except ImportError:
    # welcome to Python3
    from tkinter import Tk
    raw_input = input

r = Tk()
r.withdraw()
r.clipboard_clear()

if len(sys.argv) < 2:
    data = sys.stdin.read()
else:
    data = ' '.join(sys.argv[1:])

r.clipboard_append(data)

if sys.platform != 'win32':
    if len(sys.argv) > 1:
        raw_input('Data was copied into clipboard. Paste and press ENTER to exit...')
    else:
        # stdin already read; use GUI to exit
        print('Data was copied into clipboard. Paste, then close popup to exit...')
        r.deiconify()
        r.mainloop()
else:
    r.destroy()

This showcases:

这展示了:

  • importing Tk across Py2 and Py3
  • 在Py2和Py3上导入Tk
  • raw_input and print() compatibility
  • raw_input和print()兼容性
  • "unhiding" Tk root window when needed
  • 需要时“取消隐藏”Tk根窗口
  • waiting for exit on Linux in two different ways.
  • 等待Linux以两种不同的方式退出。

#10


1  

PyQt5:

PyQt5:

from PyQt5.QtWidgets import QApplication
from PyQt5 import QtGui
from PyQt5.QtGui import QClipboard
import sys


def main():


    app=QApplication(sys.argv)
    cb = QApplication.clipboard()
    cb.clear(mode=cb.Clipboard )
    cb.setText("Copy to ClipBoard", mode=cb.Clipboard)
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

#11


1  

This is an altered version of @Martin Thoma's answer for GTK3. I found that the original solution resulted in the process never ending and my terminal hung when I called the script. Changing the script to the following resolved the issue for me.

这是@Martin Thoma对GTK3的回答的改进版本。我发现原始解决方案导致进程永无止境,当我调用脚本时我的终端挂起。将脚本更改为以下内容为我解决了问题。

#!/usr/bin/python3

from gi.repository import Gtk, Gdk
import sys
from time import sleep

class Hello(Gtk.Window):

    def __init__(self):
        super(Hello, self).__init__()

        clipboardText = sys.argv[1]
        clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
        clipboard.set_text(clipboardText, -1)
        clipboard.store()


def main():
    Hello()



if __name__ == "__main__":
    main()

You will probably want to change what clipboardText gets assigned to, in this script it is assigned to the parameter that the script is called with.

您可能希望更改为其分配的clipboardText,在此脚本中将其分配给调用脚本的参数。

On a fresh ubuntu 16.04 installation, I found that I had to install the python-gobject package for it to work without a module import error.

在新的ubuntu 16.04安装中,我发现我必须安装python-gobject包才能在没有模块导入错误的情况下工作。

#12


0  

Best way

最好的办法

import win32clipboard

win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText("Text here")
win32clipboard.CloseClipboard()

#1


77  

See Pyperclip. Example (taken from Pyperclip site):

见Pyperclip。示例(取自Pyperclip站点):

import pyperclip
pyperclip.copy('The text to be copied to the clipboard.')
spam = pyperclip.paste()

Also, see Xerox. But it appears to have more dependencies.

另外,请参阅Xerox。但它似乎有更多的依赖。

#2


30  

On mac i use this function.

在Mac上我使用此功能。

import os 
data = "hello world"
os.system("echo '%s' | pbcopy" % data)

It will copy "hello world" to the clipboard.

它会将“hello world”复制到剪贴板。

#3


26  

Use Tkinter:

使用Tkinter:

https://*.com/a/4203897/2804197

https://*.com/a/4203897/2804197

try:
    from Tkinter import Tk
except ImportError:
    from tkinter import Tk
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()

(Original author: https://*.com/users/449571/atomizer)

(原作者:https://*.com/users/449571/atomizer)

#4


11  

Pyperclip seems to be up to the task.

Pyperclip似乎可以胜任这项任务。

#5


7  

To use native Python directories, use:

要使用本机Python目录,请使用:

import subprocess

def copy2clip(txt):
    cmd='echo '+txt.strip()+'|clip'
    return subprocess.check_call(cmd, shell=True)

Then use:

然后使用:

copy2clip('This is on my clipboard!')

to call the function.

调用该函数。

#6


4  

This is the only way that worked for me using Python 3.5.2 plus it's the easiest to implement w/ using the standard PyData suite

这是使用Python 3.5.2的唯一方法,使用标准PyData套件最容易实现

Shout out to https://*.com/users/4502363/gadi-oron for the answer (I copied it completely) from How do I copy a string to the clipboard on Windows using Python?

请大声向https://*.com/users/4502363/gadi-oron寻求答案(我完全复制了),如何使用Python将字符串复制到Windows上的剪贴板?

import pandas as pd
df=pd.DataFrame(['Text to copy'])
df.to_clipboard(index=False,header=False)

I wrote a little wrapper for it that I put in my ipython profile <3

我为它写了一个小包装器,我把它放在我的ipython配置文件中<3

#7


3  

GTK3:

GTK3:

#!/usr/bin/python3

from gi.repository import Gtk, Gdk


class Hello(Gtk.Window):

    def __init__(self):
        super(Hello, self).__init__()
        clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
        clipboard.set_text("hello world", -1)
        Gtk.main_quit()


def main():
    Hello()
    Gtk.main()

if __name__ == "__main__":
    main()

#8


3  

I try this clipboard 0.0.4 and it works well.

我尝试这个剪贴板0.0.4,它运作良好。

https://pypi.python.org/pypi/clipboard/0.0.4

https://pypi.python.org/pypi/clipboard/0.0.4

import clipboard
clipboard.copy("abc")  # now the clipboard content will be string "abc"
text = clipboard.paste()  # text will have the content of clipboard

#9


2  

One more answer to improve on: https://*.com/a/4203897/2804197 and https://*.com/a/25476462/1338797 (Tkinter).

还有一个改进的答案:https://*.com/a/4203897/2804197和https://*.com/a/25476462/1338797(Tkinter)。

Tkinter is nice, because it's either included with Python (Windows) or easy to install (Linux), and thus requires little dependencies for the end user.

Tkinter很好,因为它包含在Python(Windows)或易于安装(Linux)中,因此对最终用户几乎没有依赖性。

Here I have a "full-blown" example, which copies the arguments or the standard input, to clipboard, and - when not on Windows - waits for the user to close the application:

在这里,我有一个“完整的”示例,它将参数或标准输入复制到剪贴板,并且 - 当不在Windows上时 - 等待用户关闭应用程序:

import sys

try:
    from Tkinter import Tk
except ImportError:
    # welcome to Python3
    from tkinter import Tk
    raw_input = input

r = Tk()
r.withdraw()
r.clipboard_clear()

if len(sys.argv) < 2:
    data = sys.stdin.read()
else:
    data = ' '.join(sys.argv[1:])

r.clipboard_append(data)

if sys.platform != 'win32':
    if len(sys.argv) > 1:
        raw_input('Data was copied into clipboard. Paste and press ENTER to exit...')
    else:
        # stdin already read; use GUI to exit
        print('Data was copied into clipboard. Paste, then close popup to exit...')
        r.deiconify()
        r.mainloop()
else:
    r.destroy()

This showcases:

这展示了:

  • importing Tk across Py2 and Py3
  • 在Py2和Py3上导入Tk
  • raw_input and print() compatibility
  • raw_input和print()兼容性
  • "unhiding" Tk root window when needed
  • 需要时“取消隐藏”Tk根窗口
  • waiting for exit on Linux in two different ways.
  • 等待Linux以两种不同的方式退出。

#10


1  

PyQt5:

PyQt5:

from PyQt5.QtWidgets import QApplication
from PyQt5 import QtGui
from PyQt5.QtGui import QClipboard
import sys


def main():


    app=QApplication(sys.argv)
    cb = QApplication.clipboard()
    cb.clear(mode=cb.Clipboard )
    cb.setText("Copy to ClipBoard", mode=cb.Clipboard)
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()

#11


1  

This is an altered version of @Martin Thoma's answer for GTK3. I found that the original solution resulted in the process never ending and my terminal hung when I called the script. Changing the script to the following resolved the issue for me.

这是@Martin Thoma对GTK3的回答的改进版本。我发现原始解决方案导致进程永无止境,当我调用脚本时我的终端挂起。将脚本更改为以下内容为我解决了问题。

#!/usr/bin/python3

from gi.repository import Gtk, Gdk
import sys
from time import sleep

class Hello(Gtk.Window):

    def __init__(self):
        super(Hello, self).__init__()

        clipboardText = sys.argv[1]
        clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
        clipboard.set_text(clipboardText, -1)
        clipboard.store()


def main():
    Hello()



if __name__ == "__main__":
    main()

You will probably want to change what clipboardText gets assigned to, in this script it is assigned to the parameter that the script is called with.

您可能希望更改为其分配的clipboardText,在此脚本中将其分配给调用脚本的参数。

On a fresh ubuntu 16.04 installation, I found that I had to install the python-gobject package for it to work without a module import error.

在新的ubuntu 16.04安装中,我发现我必须安装python-gobject包才能在没有模块导入错误的情况下工作。

#12


0  

Best way

最好的办法

import win32clipboard

win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText("Text here")
win32clipboard.CloseClipboard()