macospython-3.xechoclipboardpbcopy

In Python3/OS X, how to pass a string with apostrophe to a terminal command?


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?


Solution

  • For apostrophes in a string:


    To get a shell-escaped version of the string: