Copying the contents of a variable to the clipboar

2020-06-03 08:18发布

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.

标签: python
4条回答
太酷不给撩
2楼-- · 2020-06-03 08:54

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.

查看更多
狗以群分
3楼-- · 2020-06-03 08:59

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)
查看更多
爱情/是我丢掉的垃圾
4楼-- · 2020-06-03 09:11

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.

查看更多
戒情不戒烟
5楼-- · 2020-06-03 09:13

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)
查看更多
登录 后发表回答