Question

I came across this code when searching for a solution. Unfortunately my rep wasn't high enough to comment so I have started a question for help.

The code below works perfectly and does exactly what I needed it to. Problem I have is aside from the 2 obvious bits def function and call function, I am not sure what it is doing. It seems to add like a "\n" newline to the copied string, as when I paste it it does a new line so I want to strip that out. Thanks in advance.

#import subprocess - ok
import subprocess
#define a function called copy2clip which takes 1 argument, txt.
def copy2clip(txt):

    #Call CMD and echo (txt) to the clip program (which is not a python program)
    cmd='echo '+txt.strip()+'|clip'

    #Check that the CMD program ran ok
    return subprocess.check_call(cmd, shell=True)

#call our function and pass it this string....
copy2clip('now this is on my clipboard')
Était-ce utile?

La solution

My guess is that there is an program called clip that reads the standard input and copies that text into the clipboard.

The rest of the program is easy: it calls the shell with the command:

echo whatever | clip

being whatever the text to be copied to the clipboard. echo copies the text to the standard input of clip and that's all!

But note that this is a terrible way of doing things! Imaging somebody manages to insert the following text into your clipboard: bye ; rm -rf /; echo haha...

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top