2

If I have a variable var = 'this is a variable'

how can I copy this string to the windows clipboard so I can simply Ctrl+v and it's transferred elsewhere? I don't want to use anything that isn't that isn't built in, I hope it's possible.

thanks!

M. A. Kishawy
  • 5,001
  • 11
  • 47
  • 72
Toby Smith
  • 1,505
  • 2
  • 15
  • 24

2 Answers2

8

You can do this:

>>> import subprocess
>>> def copy2clip(txt):
...    cmd='echo '+txt.strip()+'|clip'
...    return subprocess.check_call(cmd, shell=True)
...
>>> copy2clip('now this is on my clipboard')
dawg
  • 98,345
  • 23
  • 131
  • 206
  • May I ask, why the down vote? – dawg Apr 05 '14 at 00:36
  • 1
    Presumably because of the danger of copying shell code like that. I wonder what `x && rm -rf / ` would do when passed to your function. – Cees Timmerman Feb 06 '15 at 12:18
  • @CeesTimmerman: By that reasoning, one would never use a subprocess call for anything. It is perfectly safe to use a subprocess if the program maintains control of what is called. Indeed, you don't even need to call subprocess to erase the disk. `shutil.rmtree()` would do it or `os.remove()` would do nicely. I think you are conflating taking user strings or using arbitrary strings and executing code with *those* vs just calling a shell call with a string constructed internally in the program. – dawg Feb 06 '15 at 17:10
  • `copy2clip` should do just that, and not erase my disk when a user attempts to copy a dangerous command. Else name it `copy2clip_unless_its_a_shell_script`. I just tried copying `|dir` and got a nice directory listing instead. `hello\nworld` also fails. – Cees Timmerman Feb 09 '15 at 12:46
  • This is *so* inherently unsafe. – John Frazer Nov 17 '17 at 21:41
  • @JohnFrazer: Please elaborate – dawg Nov 17 '17 at 22:29
5

Pyperclip provides a cross-platform solution.

One note about this module: It encodes strings into ASCII, so you made need to perform some encoding/decoding work on your strings to match it prior running it through Pyperclip.

Example:

import pyperclip

#Usual Pyperclip usage:
string = "This is a sample string."
pyperclip.copy(string)
spam = pyperclip.paste()

#Example of decoding prior to running Pyperclip:
strings = open("textfile.txt", "rb")
strings = strings.decode("ascii", "ignore")
pyperclip.copy(strings)
spam = pyperclip.paste()

Probably an obvious tip but I ran into trouble until I looked at Pyperclip's code.

KAG1224
  • 161
  • 1
  • 6