how can I copy a string to the windows clipboard? python 3 [duplicate]

喜你入骨 提交于 2019-12-24 03:34:28

问题


If I have a variable var = 'this is a variable'

how can I copy this string to the windows clipboard so I can simply Ctrl+v and it's transferred elsewhere? I don't want to use anything that isn't that isn't built in, I hope it's possible.

thanks!


回答1:


You can do this:

>>> import subprocess
>>> def copy2clip(txt):
...    cmd='echo '+txt.strip()+'|clip'
...    return subprocess.check_call(cmd, shell=True)
...
>>> copy2clip('now this is on my clipboard')



回答2:


Pyperclip provides a cross-platform solution.

One note about this module: It encodes strings into ASCII, so you made need to perform some encoding/decoding work on your strings to match it prior running it through Pyperclip.

Example:

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()

Probably an obvious tip but I ran into trouble until I looked at Pyperclip's code.



来源:https://stackoverflow.com/questions/20573990/how-can-i-copy-a-string-to-the-windows-clipboard-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!