Copy string to clipboard natively python 3

Question:

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.

Asked By: Binyamin

||

Answers:

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.

Answered By: Binyamin

I wanted a native solution too but the ones I found had me struggled with UTF-16 Encoding and including a BOM.
I solved it with:

import subprocess    
subprocess.run(['clip.exe'], input=txt.encode('UTF-16LE'), check=True)

on Windows

Answered By: Dr_DragonKiller
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.