pythonespeak

shows error " sh: 1: Syntax error: Unterminated quoted string " in python


#!/usr/bin/env python3
from os import system

def playSong():
    message = "it's time to drink water and, take a rest for some minutes."
    #filepath = "/home/leader/Downloads/anywhere.mp3"
    system("espeak '" + message + "'")

playSong()

while running this program in terminal it shows this error. How can i get rid of this?


Solution

  • Do not ever use system() -- in any language, not just Python -- without a string that has been explicitly written and audited to be valid, safe shell script, and which cannot have uncontrolled contents substituted into it.

    When you need to pass arguments through, use the subprocess module instead:

    #!/usr/bin/env python3
    import subprocess
    
    def playSong():
        message = "it's time to drink water and, take a rest for some minutes."
        #filepath = "/home/leader/Downloads/anywhere.mp3"
        p = subprocess.Popen(['espeak', message])
        p.wait()
    
    playSong()
    

    Otherwise, you would have a very bad day when someone tries to play the message Do not ever run $(rm -rf ~) (or its more deliberately-malicious variant $(rm -rf ~)'$(rm -rf ~)').