2

如果我有一个变量 var = '这是一个变量'

如何将此字符串复制到 Windows 剪贴板,以便我可以简单地 Ctrl+v 并将其转移到其他地方?我不想使用任何不是内置的东西,我希望这是可能的。

谢谢!

4

2 回答 2

8

你可以这样做:

>>> import subprocess
>>> def copy2clip(txt):
...    cmd='echo '+txt.strip()+'|clip'
...    return subprocess.check_call(cmd, shell=True)
...
>>> copy2clip('now this is on my clipboard')
于 2013-12-13T23:27:12.450 回答
5

Pyperclip提供了一个跨平台的解决方案。

关于此模块的一个注意事项:它将字符串编码为 ASCII,因此在通过 Pyperclip 运行它之前,您需要对字符串执行一些编码/解码工作以匹配它。

例子:

import pyperclip

#Usual Pyperclip usage:
string = "This is a sample string."
pyperclip.copy(string)
spam = pyperclip.paste()

#Example of decoding prior to running Pyperclip:
strings = open("textfile.txt", "rb")
strings = strings.decode("ascii", "ignore")
pyperclip.copy(strings)
spam = pyperclip.paste()

可能是一个明显的提示,但在查看 Pyperclip 的代码之前我遇到了麻烦。

于 2014-02-25T03:27:25.950 回答