Search code examples
pythonwindowsclipboard

Copy string to clipboard natively python 3


I looked for a long time for a good method to put a string on the clipboard, using only the directories included in python. I tried

import subprocess
def copy2clip(txt):
    cmd='echo '+txt.strip()+'|clip'
    return subprocess.check_call(cmd, shell=True)

and then calling

copy2clip('text')

However this seemed to add an extra line to the text on the clipboard.

I also tried the Tkinter method, but it just made the python window crash when I tried to paste.

I am running python 3.5.2 on windows 10.


Solution

  • I used

    import subprocess
    txt = "Save to clipboard!"
    subprocess.run(['clip.exe'], input=txt.strip().encode('utf-16'), check=True)
    

    worked perfectly. Thanks @eryksun for commenting this answer.