简体   繁体   中英

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''')

Alternatively, open the process with Popen(...).pid and then use os.kill()

my_pid = Popen('/home/rolf/test1.sh',).pid
os.kill(int(my_pid), signal.SIGKILL)

Remember to include a shebang in your script (#!/bin/sh)

Edit: On second thoughts, perhaps

os.kill(int(my_pid), signal.SIGTERM)

is probably a better way to end the process, it at least gives the process the chance to close down gracefully.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM