Copy variable contents to clipboard

I am trying to copy the contents of a variable to the clipboard automatically in a python script. So, a variable is created that contains the string, and I would like to copy this string to the clipboard.

Is there a way to do this with Pyclips or

os.system("echo '' | pbcopy") 

I tried passing the variable where the line should go, but this does not work, which makes sense to me.

+4
source share
4 answers

Have you tried this?

 import os def addToClipBoard(text): command = 'echo ' + text.strip() + '| clip' os.system(command) 

Read more about solutions here .

Edit:

You can call it like:

 addToClipBoard(your_variable) 
+6
source

For X11 (Unix / Linux):

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

xsel also gives you the ability to write:

  • primary selection (default)

  • secondary selection ( -s ) or

  • clipboard (option -b ).

If xsel does not work as you expect, probably because you are using the wrong choice / clipboard.

In addition, with the -a option, you can add to the clipboard instead of overwriting. Using -c clears the clipboard.

Improvement

The subprocess module provides a safer way to do the same:

 from subprocess import Popen, PIPE Popen(('xsel', '-i'), stdin=PIPE).communicate(variable) 
+1
source

The accepted answer did not work for me, because the output was quotation marks, apostrophes, and $$ characters, which were interpreted and replaced by the shell.

I improved the function based on the answer. This solution uses a temporary file instead of an echo line 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 pbcopy with clip for Windows or xclip for Linux.

+1
source

Since you mentioned PyCLIPS, it sounds like third-party packages are on the table. Let me give a recommendation for pyperclip . Full documentation can be found on GitHub, but here is 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 can cause complex string problems, and pyperclip provides the same cross-platform API.

0
source

Source: https://habr.com/ru/post/1262394/


All Articles