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

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()

而 运行 该程序在终端中显示此错误。我怎样才能摆脱这个?

试试这个,用 \

转义单引号
message = "it\'s time to drink water and, take a rest for some minutes."

system('espeak "%s"' %message)

永远不要使用 system()——在任何语言中,而不仅仅是 Python——如果没有明确编写和审核为有效、安全的字符串 shell 脚本, 并且不能有不受控制的内容代入其中。

当您需要传递参数时,请改用 subprocess 模块:

#!/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()

否则,当有人试图播放消息 Do not ever run $(rm -rf ~)(或其更故意恶意的变体 $(rm -rf ~)'$(rm -rf ~)')时,您的日子会很糟糕。