gpt4 book ai didi

python - Popen.communicate 转义我发送到 stdin 的字符串

转载 作者:行者123 更新时间:2023-11-30 23:39:47 30 4
gpt4 key购买 nike

我正在尝试使用 Popen 生成一个进程,并将其发送一个特定的字符串到它的 stdin

我有:

pipe = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE)
pipe.communicate( my_stdin_str.encode(encoding='ascii') )
pipe.stdin.close()

但是,第二行实际上转义了 my_stdin_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-

关于python - Popen.communicate 转义我发送到 stdin 的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13260061/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com