1

Working on a python project where I need to copy a string to the clipboard for the user to use on other applications based on inputs. Right now I have the following:

os.system(f"echo {phrase}| clip")

for now it works fine within the python console, but whenever I do a ctrl+v/right-click+paste function it will paste the {phrase} but also include a new line right below it which throws off the other applications.

I've tried using str.strip() and str.rstrip() on {phrase} but it doesn't make a difference. Any help would be appreciated.

RTShields
  • 43
  • 1
  • 1
  • 6
  • Which operating system? There are APIs available to manipulate the clipboard directly, without using a shell hack. – Tim Roberts Mar 09 '23 at 17:48
  • 1
    It's `echo` that's adding the newline; nothing you can possibly do with `phrase` will change that. You need to issue the command as `echo -n {phrase}` - but note that there will still be issues if your string includes spaces or other characters that are meaningful to the shell. It would be better to use the `pyperclip` module, which works on multiple systems, and knows how to deal with such issues. – jasonharper Mar 09 '23 at 17:49
  • @jasonharper - I've just tried using the -n flag, doesn't seem to help, and without admin privileges I can't pip in pyperclip. I went with a different response and it worked well. :) – RTShields Mar 09 '23 at 18:07

1 Answers1

5

The issue is echo prints out a newline by default; add the -n switch to make it not to.

HOWEVER, DON'T DO THIS:

os.system(f"echo -n {phrase} | clip")

because if phrase contains malicious user input, you've got a (remote) code execution vulnerability at your hands (consider | somethingevil).

Instead, use subprocess.run() with input, which does the same as piping from echo to clip, and you don't need echo at all.

subprocess.run("clip", input=phrase, check=True, encoding="utf-8")

Better still, you could use the pyperclip module:

pyperclip.copy('The text to be copied to the clipboard.')
AKX
  • 152,115
  • 15
  • 115
  • 172