简体   繁体   中英

Python - Copy LISTS to Clipboard

I have some Python code that produces a list like this:

[(('infection',), 548), (('data',), 543), (('plant',), 514), (('host',), 513), (('species',), 489)]

I want the code to copy this list to my clipboard in that exact format ie, the same as if I was to print the list.

However, the packages I have found ie clipboard, pyperclip do NOT allow lists to be copied.

I can join the list into a string, but then I lose the brackets and commas etc (or its a faff to add them back in).

Is there a package or a nifty bit of code that can copy LISTS to the clipboard?

Many thanks

Maybe this will help:

import os
def addToClipBoard(text):
    command = 'echo ' + text.strip() + '| clip'
    os.system(command)
lst = [...] #your list
addToClipBoard(str(lst))

Here's a quick example for macOS based on this ) that doesn't require additional packages.

 import subprocess list_to_put_on_clipboard = [(('infection',), 548), (('data',), 543), (('plant',), 514), (('host',), 513), (('species',), 489)] list_as_str = '\n'.join([str(item) for item in list_to_put_on_clipboard]) subprocess.run("pbcopy", universal_newlines=True, input=list_as_str)

Here is the result when copying to excel

Notes:

  • Not all types may support conversion to str
  • You may want to use a different delimiter than '\n' above, but '\n' produces what I think is the desired Excel output in this case

For other operating systems , according to comments in the above link, instead of "pbcopy" use:

  • "xclip" for Linux
  • "clip" for Windows

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM