繁体   English   中英

在python字符串中转义引号

[英]Escaping quotation marks in python string

我正在使用subprocess进程在python中调用程序,并向其传递了一个字符串,该字符串可以包含引号。

这是给我带来麻烦的代码

import subprocess
text = subprocess.Popen("""awk 'BEGIN { print "%s"}' | my_program """ % sentence, stdout=subprocess.PIPE, shell=True)

sentence = "I'm doing this"我收到以下错误消息

/bin/sh: -c: line 0: unexpected EOF while looking for matching `"'
/bin/sh: -c: line 1: syntax error: unexpected end of file

我想这与python和linux中引号转义的方式有关。 有办法解决吗?

您混淆了awk和底层shell,因为在引用的awk表达式中有一个引号。 第一部分等效于:

awk 'BEGIN { print "I'm doing this"}'

即使在纯外壳中,这也是不正确的。

快速修复,请转义句子中的引号:

text = subprocess.Popen("""awk 'BEGIN { print "%s"}' | my_program """ % sentence.replace("'","\\'"), stdout=subprocess.PIPE, shell=True)

正确的解决方法:根本不用awk来打印某些东西,只需将输入馈送到您的子流程中即可:

text = subprocess.Popen(my_program, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
output,error = text.communicate(sentence.encode())

(并且您可以在此过程中摆脱掉shell=True

最后一点:您似乎遇到了麻烦,因为my_program是一些程序加参数。 要传递诸如aspell -a类的命令,您可以执行以下操作:

my_program = "aspell -a"

要么:

my_program = ['aspell','-a']

不是

my_program = ['aspell -a']

这可能就是您在此处所做的,因此Python尝试从字面上执行程序"aspell -a"而不是拆分为program + arguments。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM