Python communicate转义我发送给stdin的字符串
我正在尝试使用Python communicate转义我发送给stdin的字符串,python,subprocess,Python,Subprocess,我正在尝试使用Popen生成一个进程,并将一个特定字符串发送到它的stdin 我有: pipe = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE) pipe.communicate( my_stdin_str.encode(encoding='ascii') ) pipe.stdin.close() 但是,第二行实际上避开了my\u stdin\u str中的空白。例如,如果我有: my_stdin_str="This is a
Popen
生成一个进程,并将一个特定字符串发送到它的stdin
我有:
pipe = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE)
pipe.communicate( my_stdin_str.encode(encoding='ascii') )
pipe.stdin.close()
但是,第二行实际上避开了my\u stdin\u str
中的空白。例如,如果我有:
my_stdin_str="This is a string"
该过程将看到:
This\ is\ a\ string
如何防止这种行为?我无法在Ubuntu上复制它:
from subprocess import Popen, PIPE
shell_cmd = "perl -pE's/.\K/-/g'"
p = Popen(shell_cmd, shell=True, stdin=PIPE)
p.communicate("This $PATH is a string".encode('ascii'))
在这种情况下,shell=True
是不必要的:
from subprocess import Popen, PIPE
cmd = ["perl", "-pE" , "s/.\K/-/g"]
p = Popen(cmd, stdin=PIPE)
p.communicate("This $PATH is a string".encode('ascii'))
两者产生相同的输出:
T-h-i-s- -$-P-A-T-H- -i-s- -a- -s-t-r-i-n-g-
除非您知道出于某种原因需要它,否则一般不要使用“shell=True”运行(这听起来像是在这里发生的事情,没有经过测试)。如果我在
bash
上使用cmd='cat'
运行您的代码,cat
不会输出任何\
。你用的是什么外壳?你能告诉我们什么是cmd
吗?@BrianCain的建议解决了问题吗?你确定你的程序不只是打印字符串的转义版本吗?我很确定python不会在这里进行任何转义。您不需要pipe.stdin.close()
pipe.communicate()
应自行关闭stdin。