Rakshith Gb Rakshith Gb - 2 months ago 11x
Bash Question

Killing a process within a python script running on linux

I have Raspbian as the linux distro running on my RPI. I've setup a small socket server using twisted and it receives certain commands from an iOS app. These commands are strings. I started a process when I received "st" and now I want to kill it when i get "sp". This is the way I tried:

  1. Imported OS

  2. Used os.system("...") //to start process

  3. os.system("...") // to kill process

Lets say the service is named xyz.
This is the exact way I tried to kill it:

os.system('ps axf | grep xyz | grep -v grep | awk '{print "kill " $1 }' | sh')

But I got a syntax error. That line runs perfectly when I try it in terminal separately. Is this a wrong way to do this in a python script? How do I fix it?


You will need to escape the quotes in your string:

os.system('ps axf | grep xyz | grep -v grep | awk \'{print "kill " $1 }\' | sh')

Or use a triple quote:

os.system('''ps axf | grep xyz | grep -v grep | awk '{print "kill " $1 }' | sh''')