0

I am doing a python3 software that use google_speech and and os.system command.

Everything work fine but when a user enter a string with the ' character I have this error : Syntax error: Unterminated quoted string

This is my code :

def textToSpeak():
global fieldValues

msg = "Enter the text to speak\n\nDon't use" +str(" \' ")+str(" write it like this : je tinvite chez moi, not je t\'invite chez moi ")
title = "Enter the text to speak"
fieldNames = ["Text to speak"]
fieldValues = []
fieldValues = multenterbox(msg, title, fieldNames)
speak()

def speak():
global lang, fieldValues
textValue = "google_speech -l" +str(lang) +str(" \'\"")+str(fieldValues[0])+str("\"\'")
os.system(textValue)
hamdy.aea
  • 3
  • 4

3 Answers3

3

If you insist on os.system, you want shlex.quote:

Return a shell-escaped version of the string s. The returned value is a string that can safely be used as one token in a shell command line, for cases where you cannot use a list.

That said, I'd strongly recommend moving to the subprocess module (subprocess.call would be the simplest replacement for os.system here, though there are other options), and passing your arguments in list form, allowing subprocess to do the work of escaping (when necessary on Windows), removing the need to manually add quotes, and avoiding string processing entirely on other OSes (where it can exec an argument vector directly, with no escapes needed).

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
1

It seems as if you're trying to escape your string input by the user.

You can use repr() for this, or json.dumps().

>>> repr("je t'invite")
'"je t\'invite"'

>>> json.dumps("je t'invite")
'"je t\'invite"'
Ben
  • 1,561
  • 4
  • 21
  • 33
0

I finally found an answer who works fine :

textValue = "google_speech -l" +str(lang) +str(" \"")+str(fieldValues[0].replace("'","\'"))+str("\"")
os.system(textValue)
hamdy.aea
  • 3
  • 4