-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
  • 200
  • 2
  • 15

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
  • 20,509
  • 2
  • 42
  • 59
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
  • 13,713
  • 3
  • 27
  • 50