1

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.

1
  • 5
    There's no need to use the shell, which is especially bad here since shell=True doesn't use the /U option that makes cmd's internal commands output Unicode. Instead the echoed output is getting best-fit encoded to the console or ANSI codepage. Consider using the new run function instead, e.g. subprocess.run(['clip.exe'], input=txt.strip().encode('utf-16'), check=True).
    – Eryk Sun
    Commented Dec 8, 2016 at 6:13

2 Answers 2

14

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.

1
  • This didn't work for me. When i pasted a multiline string into ipython it said "ValueError: source code string cannot contain null bytes". Any Ideas? Commented Apr 21, 2021 at 15:34
0

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.