运行 通过 python 子进程搜索并用 sed 替换导致无法查看的字符

Running search and replace with sed via python subprocess results in unviewable characters

给定文件 /tmp/hi,内容为:bali=${hi

和运行上面的命令sed -i -E 's/(^|[^.])hi/bi/g' /tmp/hi

按预期在bali=${bi中产生以下内容。

但是,运行里面的sed命令python3.5子进程:

import subprocess
subprocess.run("sed -i -E 's/(^|[^.])hi/bi/g' /tmp/hi", shell=True)

结果如下内容:

检查了 vi 中的文件,它显示:bali=$^Abi

为什么会这样以及如何使用 python3.5 子进程实现相同的文件内容?

那是因为 </code> 正在被 Python 解释。如果您想使用转义序列而不必转义它们,则需要使用原始字符串语法 (<code>r"some string with escape sequences"):

Python 3.5.3 (default, Jan 19 2017, 14:11:04)
[GCC 6.3.0 20170118] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> print("sed -i -E 's/(^|[^.])hi/bi/g' /tmp/hi")
sed -i -E 's/(^|[^.])hi/bi/g' /tmp/hi
>>> print(r"sed -i -E 's/(^|[^.])hi/bi/g' /tmp/hi")
sed -i -E 's/(^|[^.])hi/bi/g' /tmp/hi