1

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?

Victor Domingos
  • 1,003
  • 1
  • 18
  • 40

2 Answers2

1

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)
Vatsal
  • 462
  • 3
  • 9
  • Is there a python function that does that kind of escaping? I am dealing with values entered into a database, so it would be better to have the code doing that conversion. – Victor Domingos Aug 19 '16 at 15:20
1

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))
    
jackjr300
  • 7,111
  • 2
  • 15
  • 25
  • I tried to implement this suggestion in my code, but I was having a hard time to figure out why it failed. I figured out that I still had to remove the single quotes just like you did, when using `shlex.quote()`. Now it works ok ;) – Victor Domingos Aug 20 '16 at 10:59