我正在使用google_speech和os.system命令的python3软件。
一切正常但是当用户输入带有'字符的字符串时我有这个错误:语法错误:未终止的引用字符串
这是我的代码:
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)
答案 0 :(得分:3)
如果您坚持使用os.system
,则需要shlex.quote
:
返回字符串s的shell转义版本。对于无法使用列表的情况,返回的值是一个可以安全地用作shell命令行中的一个标记的字符串。
那就是说,我强烈建议转移到the subprocess
module(subprocess.call
将是os.system
最简单的替代,虽然还有其他选项),并在列表中传递你的参数表单,允许subprocess
执行转义工作(必要时在Windows上),无需手动添加引号,并完全避免在其他操作系统上进行字符串处理(可以exec
直接参数向量,不需要逃脱)。
答案 1 :(得分:1)
好像你正试图逃避用户的字符串输入。
您可以使用repr()
或json.dumps()
。
>>> repr("je t'invite")
'"je t\'invite"'
>>> json.dumps("je t'invite")
'"je t\'invite"'
答案 2 :(得分:0)
我终于找到了一个合适的答案:
textValue = "google_speech -l" +str(lang) +str(" \"")+str(fieldValues[0].replace("'","\'"))+str("\"")
os.system(textValue)