Skip to content Skip to sidebar Skip to footer

Invalid Char In Expression Awk, Python

I have a command that looks like this: ps v -p 2585 | awk '{if ($9 != '%MEM') {print $9}}' Now this runs fine in bash, it just takes the memory portion of whatever pid you give it

Solution 1:

You don't need to protect the awk commands from the shell when you're running it via popen (the arguments are already split into a list, so your whitespace is left alone).

cmd2 = ['awk', '{if ($9 != "%MEM") {print $9}}']

will work fine.


Note for future reference

Python has some nice ways of writing strings that avoid escaping like you tried to do here, for situations where you do need it:

'''In this string, I don't need to escape a single ' character,
   or even a new-line, because the string only ends
   when it gets three ' characters in a row like this:'''"""The same is true of double-quotes like this.
Of course, whitespace and both the ' and " quote characters
are safe in here."""

Solution 2:

When you run the command in bash, bash removes the single quotes and gives awk the first argument:

{if ($9 != "%MEM") {print $9}}

You are giving it single quotes, which you ought not do. You should just write:

cmd2 = ['awk', '{if ($9 != "%MEM") {print $9}}']

Post a Comment for "Invalid Char In Expression Awk, Python"