Python 3在系统调用中转义引号

时间:2018-04-25 12:44:18

标签: python

我正在尝试通过使用os.system运行Awk命令将文本文件中的新行转换为字符串中的“\ n”字符:

awk '{printf "%s\\n", $0}' /tmp/file

我的问题是转义引号不起作用:

$ replace = "awk '{printf \"%s\\n\", $0}' /tmp/file"
$ print(replace)
awk '{printf "%s\n", $0}' /tmp/file

我也尝试过使用shlex:

$ import shlex
$ line = "awk '{printf \"%s\\n\", $0}'"
$ lexer = shlex.shlex(line, posix=True)
$ lexer.escapedquotes = "'\""
$ mystring = ','.join(lexer)
$ print(mystring)
awk,{printf "%s\n", $0}

我要么知道如何用Python运行这个awk命令,要么如何将文件中的回车/换行转换为字符串中的“\ n”。

编辑:这是一个示例文件:

oneline
twoline

threeline

方法应该从此文件返回以下内容:

oneline\ntwoline\n\nthreeline

1 个答案:

答案 0 :(得分:2)

在这种情况下,您可以使用原始前缀+三重引用:

s = r"""awk '{printf "%s\\n", $0}' /tmp/file"""
print(s)

结果:

awk '{printf "%s\\n", $0}' /tmp/file

所以os.system(s)有效。

在纯python中,用文字\n替换换行符(改编自another answer of mine):

with open(file1,"rb") as f:
   contents = f.read().replace(b"\n",b"\\n")
with open(file1+".bak","wb") as f:
   f.write(contents)
os.remove(file1)
os.rename(file1+".bak",file1)