在python字符串中转义引号

时间:2017-03-27 09:30:24

标签: python string escaping

我使用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中转义引号的方式有关。有办法解决吗?

1 个答案:

答案 0 :(得分:1)

你混淆了awk和底层shell,因为引用的awk表达式中有引号。第一部分相当于:

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

哪个不正确,即使在纯shell中也是如此。

Quickfix,转义句子中的引号:

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",而不是分成程序+参数。

相关问题