Python script to copy text to clipboard [duplicate

2020-01-24 03:57发布

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

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?

11条回答
Summer. ? 凉城
2楼-- · 2020-01-24 04:09

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

Shout out to https://stackoverflow.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?

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

查看更多
姐就是有狂的资本
3楼-- · 2020-01-24 04:09

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()
查看更多
啃猪蹄的小仙女
4楼-- · 2020-01-24 04:09

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()
查看更多
该账号已被封号
5楼-- · 2020-01-24 04:17

On macOS, use subprocess.run to pipe your text to pbcopy:

import subprocess 
data = "hello world"
subprocess.run("pbcopy", universal_newlines=True, input=data)

It will copy "hello world" to the clipboard.

查看更多
小情绪 Triste *
6楼-- · 2020-01-24 04:20

See Pyperclip. Example (taken from Pyperclip site):

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.

查看更多
来,给爷笑一个
7楼-- · 2020-01-24 04:21

I try this clipboard 0.0.4 and it works well.

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
查看更多
登录 后发表回答