In Python, kill the process by name in Linux.

Source: Internet
Author: User
In Python, kill the process by name under Linux-general Linux technology-Linux programming and kernel information. For details, see the following. In Linux, it is a little troublesome to kill the process by the command name of the process. I wrote a simple tool using python. However, there is still a small problem with this tool, that is, simply enter a name, executing the ps aux | grep % name command also generates a process, but the process disappears immediately and cannot be found in the kill operation. However, the running results are satisfactory.

Xkill
#! /Usr/bin/python

Import OS, re, sys

Def kill_by_name (name ):
Cmd = 'ps aux | grep % s' % name
F = OS. popen (cmd)
Regex = re. compile (R' \ w + \ s + (\ d +) \ s + .*')
Txt = f. read ()
If len (txt) <5:
Print 'there is no thread by name or command % s' % name
Return

Ids = regex. findall (txt)
Cmd = "kill % s" % ''. join (ids)
OS. system (cmd)


If _ name __= = '_ main __':
If len (sys. argv) = 1:
Name = raw_input ("type the process command name :")
Else:
Name = sys. argv [1]
Kill_by_name (name)
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.