62393

Question:
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)
I am having the following traceback:
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)
How do I make it run correctly?
Answer1: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)
<a href="https://docs.python.org/2/library/string.html#format-string-syntax" rel="nofollow">https://docs.python.org/2/library/string.html#format-string-syntax</a>
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 }}
.