I have a Python 3 application that should at some point put a string into the clipboard. I am using system commands echo
and pbcopy
and it works properly. However, when the string includes an apostrophe (and who knows, maybe other special characters), it exits with an error. Here is a code sample:
import os
my_text = "Peoples Land"
os.system("echo '%s' | pbcopy" % my_text)
It works ok. But if you correct the string to "People's Land", it returns this error:
sh: -c: line 0: unexpected EOF while looking for matching `''
sh: -c: line 1: syntax error: unexpected end of file
I guess I need to somehow encode the string before passing it to the shell commands, but I still don't know how. What is the best way to accomplish this?
For apostrophes in a string:
'%r'
instead of '%s'
my_text = "People's Land" os.system("echo '%r' | pbcopy" % my_text)
To get a shell-escaped version of the string:
You can use shlex.quote()
import os, shlex my_text = "People's Land, \"xyz\", hello" os.system("echo %s | pbcopy" % shlex.quote(my_text))