-1

Some error are reported, when format string that is a shell command.

The python code:

str = "jps | grep {0} | grep -v {1} | awk '{print $1}' | xargs kill -9".format(1,2)

The error information:

Traceback (most recent call last):
File "<stdin>", line 1, in <module> KeyError: 'print'

How to fix it?

sol
  • 225
  • 4
  • 17

2 Answers2

2

Use:

>>> "jps | grep {0} | grep -v {1} | awk '{{print $1}}' | xargs kill -9".format(1,2)
"jps | grep 1 | grep -v 2 | awk '{print $1}' | xargs kill -9"
donkopotamus
  • 22,114
  • 2
  • 48
  • 60
1

Answering the title

In Python 2.7, print is a keyword. In Python 3.x, it is not.

Fixing the code

"jps | grep {0} | grep -v {1} | awk '{{print $1}}' | xargs kill -9".format(1,2)

Why

When you wrap a value inside of extra {} in format, it will interpret the string literally, not trying to replace it.

Neil
  • 14,063
  • 3
  • 30
  • 51