Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying the contents of a variable to the clipboard

Tags:

python

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.

like image 240
Alex Avatar asked Dec 29 '13 03:12

Alex


4 Answers

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)
like image 183
Christian Tapia Avatar answered Oct 11 '22 03:10

Christian Tapia


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.

like image 44
Matt Kahl Avatar answered Oct 11 '22 02:10

Matt Kahl


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.

like image 4
P. Šileikis Avatar answered Oct 11 '22 04:10

P. Šileikis


For X11 (Unix/Linux):

os.system('echo "%s" | xsel -i' % variable)

xsel also gives you a choice of writing to:

  1. the primary selection (default)

  2. the secondary selection (-s option), or

  3. 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.

Improvement

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)
like image 2
John1024 Avatar answered Oct 11 '22 02:10

John1024