Copy string - Python

Ok guys, I think it’s easy, but I can’t find a way to copy the line. Just use COPY for the system, such as CTRL + C, in the text.

Basically, I want to copy a string so that I can, for example, say, paste (ctrl + v).

Sorry for such a trivial question, haha.

+3
source share
4 answers

It is highly OS dependent. On Linux, because of the unusual X selection model, the easiest way is to use popen('xsel -pi')and write text to this channel.

For example: (I think)

def select_xsel(text):
    import subprocess
    xsel_proc = subprocess.Popen(['xsel', '-pi'], stdin=subprocess.PIPE)
    xsel_proc.communicate(some_text)

As pointed out in the comments, on a Mac you can use a command /usr/bin/pbcopylike:

xsel_proc = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE)

, os.name, , :

import os, subprocess
def select_text(text):
    if os.name == "posix":
        # try Mac first
        try:
            xsel_proc = subprocess.Popen(['pbcopy'], stdin=subprocess.PIPE)
        except:
            # try Linux version
            xsel_proc = subprocess.Popen(['xsel', '-pi'], stdin=subprocess.PIPE)
    elif os.name == "nt":
        # Windows...
+2

Windows win32clipboard. pywin32.

GTK ( , GNU/Linux) pygtk.

EDIT: ( ), wxPython, , wx.Clipboard.

+4

Windows , , ..

+2

For a multi-platform solution, you will need to use a cross-platform infrastructure such as wxPython or PyQt, both of which support reading and writing to the system clipboard, regardless of platform.

+2
source

Source: https://habr.com/ru/post/1740604/


All Articles