[英]Escaping quotation marks in python string
I'm using subprocess
to call a program within python and I'm passing a string to it, which can contain quotation marks. 我正在使用
subprocess
进程在python中调用程序,并向其传递了一个字符串,该字符串可以包含引号。
This is the piece of code that is giving me troubles 这是给我带来麻烦的代码
import subprocess
text = subprocess.Popen("""awk 'BEGIN { print "%s"}' | my_program """ % sentence, stdout=subprocess.PIPE, shell=True)
When sentence = "I'm doing this"
I get the following error message 当
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
I guess this has to do with the way quotes are escaped in python and linux. 我想这与python和linux中引号转义的方式有关。 Is there a way to fix it?
有办法解决吗?
you're confusing awk
and underlying shell because there's a quote in your quoted awk expression. 您混淆了
awk
和底层shell,因为在引用的awk表达式中有一个引号。 First part is equivalent to: 第一部分等效于:
awk 'BEGIN { print "I'm doing this"}'
Which is incorrect, even in pure shell. 即使在纯外壳中,这也是不正确的。
Quickfix, escape the quotes in your sentence: 快速修复,请转义句子中的引号:
text = subprocess.Popen("""awk 'BEGIN { print "%s"}' | my_program """ % sentence.replace("'","\\'"), stdout=subprocess.PIPE, shell=True)
Proper fix: don't use awk
at all just to print something, just feed input to your subprocess: 正确的解决方法:根本不用
awk
来打印某些东西,只需将输入馈送到您的子流程中即可:
text = subprocess.Popen(my_program, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
output,error = text.communicate(sentence.encode())
(and you can get rid of the shell=True
in the process) (并且您可以在此过程中摆脱掉
shell=True
)
Last point: you seem to have trouble because my_program
is some program plus arguments. 最后一点:您似乎遇到了麻烦,因为
my_program
是一些程序加参数。 To pass a command such as aspell -a
you can do: 要传递诸如
aspell -a
类的命令,您可以执行以下操作:
my_program = "aspell -a"
or: 要么:
my_program = ['aspell','-a']
but not 但不是
my_program = ['aspell -a']
which is probably what you've done here, so Python tries to literally execute the program "aspell -a"
instead of splitting into program + argument. 这可能就是您在此处所做的,因此Python尝试从字面上执行程序
"aspell -a"
而不是拆分为program + arguments。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.