Python: A small program, how to delete a group of processes, and only provide the program name without the pid.

Source: Internet
Author: User

We often use 'ps-e | grep name' or 'ps-e | awk'/name/{print $1} ''in shell to find the pid of a process, then, use 'sudo kill-8 XXX' to delete the process (we found that 'sudo killall name' cannot effectively Delete the process ). However, you may need to delete multiple processes and execute the preceding commands repeatedly. Bash can well complete the tasks of deleting processes in batches.
But here I want to discuss the solution in python. The subprocess module of python is used here.
 
1 #! /Usr/bin/env python
2
3 import OS
4 import sys
5 import getopt
6 import subprocess
7
8 def usage ():
9 print "killnames ..."
10 sys. exit (2)
11
12 def kill_names ():
13 try:
14 opts, args = getopt. getopt (sys. argv [1:], "")
15 TB t GetoptError, err:
16 usage ()
17
18 if not args:
19 print "Please input process name"
20 sys. exit (2)
21 # join List to string
22 myparam = "|". join (args)
23 # get the infos of working processes
24 myps = subprocess. Popen (["ps", "-e"], stdout = subprocess. PIPE, stderr = subprocess. PIPE)
25 # get List of pids
26 mypids = subprocess. popen (["awk", "/% s/{print $1}" % myparam], stdin = myps. stdout, stdout = subprocess. PIPE, stderr = subprocess. PIPE ). communicate () [0]. strip (). split ("\ n ")
27
28 for mypid in mypids:
29 OS. system ("sudo kill-8% s" % s mypid)
30
31
32 if _ name __= = '_ main __':
33 kill_names ()
 

 

From CCJPP

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.