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.
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.
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
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.
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.
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