Ways to get process PID numbers using Python _python

Source: Internet
Author: User

After saving as a. py file, run the script to add the process name later. For example: Python proinfo.py QQ can get information on the process of QQ, note that the case is not case-sensitive

Copy Code code as follows:
#-*-Encoding:utf-8-*-
Import OS
Import Sys
Import string
Import Psutil
Import re

def get_pid (name):
Process_list = Psutil.get_process_list ()
Regex = "pid= (\d+), \sname=\ '" + name + "\"
Print Regex
PID = 0
For line in Process_list:
Process_info = str (line)
Ini_regex = Re.compile (regex)
result = Ini_regex.search (process_info)
If result!= None:
PID = String.atoi (Result.group (1))
Print Result.group ()
Break
def main (argv):<br> name = argv[1]<br> get_pid (name)

if __name__ = = "__main__":
Main (SYS.ARGV)

Code Description:

1.import Psutil need to be installed to get the Linux process list

Copy Code code as follows:
Process_list = Psutil.get_process_list () #获取进程列表

2.import Re:python processing of regular modules

Copy Code code as follows:
Regex = "pid= (\d+), \sname=\ '" + name + "\" #组成string类型的正则表达式
Ini_regex = Re.compile (regex) #初始化正则表达式
result = Ini_regex.search (process_info) #正则表达式匹配
Result.group (0): The contents of the entire string matched to
Result.group (1): match the contents of the first ()

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.