I am trying to copy the contents of a variable to the clipboard automatically within a python script. So, a variable is created that holds a string, and I'd like to copy that string to the clipboard.
Is there a way to do this with Pyclips or
os.system("echo '' | pbcopy")
I've tried passing the variable where the string should go, but that doesn't work which makes sense to me.
Have you tried this?
import os
def addToClipBoard(text):
command = 'echo ' + text.strip() + '| clip'
os.system(command)
Read more solutions here.
Edit:
You may call it as:
addToClipBoard(your_variable)
Since you mentioned PyCLIPS, it sounds like 3rd-party packages are on the table. Let me thrown a recommendation for pyperclip. Full documentation can be found on GitHub, but here's an example:
import pyperclip
variable = 'Some really "complex" string with\na bunch of stuff in it.'
pyperclip.copy(variable)
While the os.system(...'| pbcopy')
examples are also good, they could give you trouble with complex strings and pyperclip provides the same API cross-platform.
The accepted answer was not working for me as the output had quotes, apostrophes and $$ signs which were interpreted and replaced by the shell.
I've improved the function based on answer. This solution uses temporary file instead of echoing the string in the shell.
def add_to_clipboard(text):
import tempfile
with tempfile.NamedTemporaryFile("w") as fp:
fp.write(text)
fp.flush()
command = "pbcopy < {}".format(fp.name)
os.system(command)
Replace the pbcopy
with clip
for Windows or xclip
for Linux.
For X11 (Unix/Linux):
os.system('echo "%s" | xsel -i' % variable)
xsel also gives you a choice of writing to:
the primary selection (default)
the secondary selection (-s
option), or
the clipboard (-b
option).
If xsel
doesn't work as you expect, it is probably because you are using the wrong selection/clipboard.
In addition, with the -a
option, you can append to the clipboard instead of overwrite. With -c
, the clipboard is cleared.
The module subprocess
provides a more secure way to do the same thing:
from subprocess import Popen, PIPE
Popen(('xsel', '-i'), stdin=PIPE).communicate(variable)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With