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.
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.
Replace the
pbcopy
withclip
for Windows orxclip
for Linux.Have you tried this?
Read more solutions here.
Edit:
You may call it as:
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:
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.For X11 (Unix/Linux):
xsel also gives you a choice of writing to:
the primary selection (default)
the secondary selection (
-s
option), orthe 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.Improvement
The module
subprocess
provides a more secure way to do the same thing: