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

758 Views Asked by At

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?

2

There are 2 best solutions below

1
On BEST ANSWER

For apostrophes in a string:

  • You can use '%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))
    
1
On

This has more to do with shell escaping actually.

Try this in commandline:

echo 'People's Land'

and this

echo 'People'\''s Land'

In python something like this should work:

>>> import os
>>> my_text = "People'\\''s Land"
>>> os.system("echo '%s' > lol" % my_text)