developer tip

텍스트를 클립 보드에 복사하는 Python 스크립트

copycodes 2020. 8. 21. 07:59
반응형

텍스트를 클립 보드에 복사하는 Python 스크립트


클립 보드에 텍스트를 복사하는 파이썬 스크립트가 필요합니다.

스크립트가 실행 된 후 다른 소스에 붙여 넣을 텍스트 출력이 필요합니다. 이 작업을 수행하는 파이썬 스크립트를 작성할 수 있습니까?


Pyperclip을 참조하십시오 . 예 (Pyperclip 사이트에서 가져옴) :

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

또한 Xerox를 참조하십시오 . 그러나 더 많은 종속성이있는 것으로 보입니다.


Mac에서는이 기능을 사용합니다.

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

"hello world"를 클립 보드에 복사합니다.


Tkinter 사용 :

https://stackoverflow.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()

(원저자 : https://stackoverflow.com/users/449571/atomizer )


이것은 나를 위해 일한 유일한 방법이며 Python 3.5.2표준 PyData제품군을 사용하여 구현하는 것이 가장 쉽습니다.

https://stackoverflow.com/users/4502363/gadi-oron외쳐서 Python을 사용하여 Windows의 클립 보드에 문자열을 어떻게 복사합니까?

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

나는 내 ipython프로필에 넣은 작은 래퍼를 썼다 <3


Pyperclip 이 작업에 달려있는 것 같습니다.


네이티브 Python 디렉터리를 사용하려면 다음을 사용하세요.

import subprocess

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

그런 다음 다음을 사용하십시오.

copy2clip('This is on my clipboard!')

함수를 호출합니다.


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()

이 클립 보드 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

개선 할 또 다른 답변 : https://stackoverflow.com/a/4203897/2804197https://stackoverflow.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.

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:

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
  • raw_input and print() compatibility
  • "unhiding" Tk root window when needed
  • waiting for exit on Linux in two different ways.

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()

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.

#!/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.

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.

참고URL : https://stackoverflow.com/questions/11063458/python-script-to-copy-text-to-clipboard

반응형