简体   繁体   English

Python - 将列表复制到剪贴板

[英]Python - Copy LISTS to Clipboard

I have some Python code that produces a list like this:我有一些 Python 代码产生这样的列表:

[(('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.但是,我发现的包,即剪贴板、pyperclip 不允许复制列表。

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?是否有 package 或可以将 LISTS 复制到剪贴板的漂亮代码?

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.是一个基于 macOS 的快速示例,不需要额外的包。

 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是复制到 excel 时的结果

Notes:笔记:

  • Not all types may support conversion to str并非所有类型都支持转换为 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您可能希望使用与上面的 '\n' 不同的分隔符,但在这种情况下,'\n' 会产生我认为是所需的 Excel output

For other operating systems , according to comments in the above link, instead of "pbcopy" use:对于其他操作系统,根据上述链接中的注释,而不是“pbcopy”使用:

  • "xclip" for Linux Linux 的“ xclip
  • "clip" for Windows Windows的“夹子”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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