[英]Running search and replace with sed via python subprocess results in unviewable characters
Given the file /tmp/hi
with content: bali=${hi
给定文件/tmp/hi
及其内容: bali=${hi
and running the command on it sed -i -E 's/(^|[^.])hi/\\1bi/g' /tmp/hi
并在其上运行命令sed -i -E 's/(^|[^.])hi/\\1bi/g' /tmp/hi
results in the following content in bali=${bi
as expected. 导致预期的bali=${bi
中的以下内容。
However, running the sed command inside python3.5 subprocess: 但是,在python3.5子进程中运行sed命令:
import subprocess
subprocess.run("sed -i -E 's/(^|[^.])hi/\1bi/g' /tmp/hi", shell=True)
results in the following content: 结果如下:
inspected the file in vi
and it shows: bali=$^Abi
在vi
检查了文件,结果显示: bali=$^Abi
Why does it happen and how to achieve the same file content using python3.5 subprocess? 为什么会发生,以及如何使用python3.5子进程实现相同的文件内容?
That's because the \\1
is being interpreted by Python. 这是因为Python正在解释\\1
。 You need to use raw string syntax ( r"some \\1 string with escape sequences"
) if you want to use escape sequences without having to escape them: 如果要使用转义序列而不必对其进行转义,则需要使用原始字符串语法( r"some \\1 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/\1bi/g' /tmp/hi")
sed -i -E 's/(^|[^.])hi/bi/g' /tmp/hi
>>> print(r"sed -i -E 's/(^|[^.])hi/\1bi/g' /tmp/hi")
sed -i -E 's/(^|[^.])hi/\1bi/g' /tmp/hi
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.