在Python中转义awk特殊字符 [英] Escape awk special character in Python

查看:176
本文介绍了在Python中转义awk特殊字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Fabric任务,如下所示:

I have a Fabric task as follows:

@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'

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

The command I want to execute on the server is:

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

但是我无法转义该行中的字符:

However I am unable to escape the characters in the line:

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)

如何使其正常运行?

推荐答案

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

The issue was solved by escaping the { and the awk new lines:

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

格式字符串包含用花括号{}包围的替换字段".花括号中不包含的所有内容均视为文字文本,该文本原样复制到输出中.如果您需要在文字文本中包含一个大括号字符,可以通过将{{}}加倍来进行转义.

Format strings contain "replacement fields" surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output. If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

这篇关于在Python中转义awk特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆