在Python中逃避awk特殊字符

时间:2016-10-25 08:55:38

标签: bash python-2.7 fabric

我有一个Fabric任务如下:

@task
def getCrons():
    timeStampNowServer = sudo("date +%s%3N", pty=False)
    cronLogFiles = sudo(
        "find /home/logs/cron/ -maxdepth 2 -type f -mtime -1 -name '*.log'", pty=False)
    cronLogFiles = cronLogFiles.splitlines(True)
    for cronLog in cronLogFiles:
        info = sudo(
            "awk '/END$/ {prev=$0; next}; /^#RETURN/ && $2>0 {cur=$0; pr=1; next}; pr {printf \" % s\n % s\n % s\n\", prev, cur, $0; pr=0}'{0}".format(cronLog), pty=False)
        print(info)

我有以下追溯:

Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/fabric/main.py", line 743, in main
    *args, **kwargs
  File "/usr/lib/python2.7/site-packages/fabric/tasks.py", line 379, in execute
    multiprocessing
  File "/usr/lib/python2.7/site-packages/fabric/tasks.py", line 274, in _execute
    return task.run(*args, **kwargs)
  File "/usr/lib/python2.7/site-packages/fabric/tasks.py", line 174, in run
    return self.wrapped(*args, **kwargs)
  File "/home/lbn/k.sewnundun/fabfile/kse/test.py", line 18, in getCrons
    "awk '/END$/ {prev=$0; next}; /^#RETURN/ && $2>0 {cur=$0; pr=1; next}; pr {printf \"%s\n%s\n%s\n\", prev, cur, $0; pr=0}'{0}".format(cronLog), pty=False)
KeyError: 'prev=$0; next'

我想在服务器上执行的命令是:

awk '/END$/ {prev=$0; next}; /^#RETURN/ && $2>0 {cur=$0; pr=1; next}; pr {printf "%s\n%s\n%s\n", prev, cur, $0; pr=0}'  mylog.LOG

但是我无法逃避行中的字符:

info = sudo(
            "awk '/END$/ {prev=$0; next}; /^#RETURN/ && $2>0 {cur=$0; pr=1; next}; pr {printf \" % s\n % s\n % s\n\", prev, cur, $0; pr=0}'{0}".format(cronLog), pty=False)

如何让它正确运行?

1 个答案:

答案 0 :(得分:2)

通过转义{和awk新行来解决问题:

info = sudo("awk '/END$/ {{prev=$0; next}}; /^#RETURN/ && $2>0 {{cur=$0; pr=1; next}}; pr {{printf \"%s\\n%s\\n%s\\n\", prev, cur, $0; pr=0}}' {0}".format(cronLog), pty=False)

https://docs.python.org/2/library/string.html#format-string-syntax

格式字符串包含由大括号{}包围的“替换字段”。大括号中未包含的任何内容都被视为文本文本,它将不加改变地复制到输出中。如果您需要在文字文本中包含大括号字符,则可以通过加倍{{}}来对其进行转义。