How to obtain the process pid using python

Source: Internet
Author: User

Save it as a. py file and run the script to add the process name after it. For example, python proinfo. py qq can obtain the process information of QQ. Note that it is case insensitive.
Copy codeThe Code is 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 needs to be installed to obtain the process list in linux
Copy codeThe Code is as follows: process_list = psutil. get_process_list () # obtain the Process List

2. import re: python's Regular Expression Processing Module
Copy codeThe Code is as follows: regex = "pid = (\ d +), \ sname = \ '" + name + "\'" # A Regular Expression of the string type
Ini_regex = re. compile (regex) # initialize a regular expression
Result = ini_regex.search (process_info) # Regular Expression matching
Result. group (0): the content of the matching string.
Result. group (1): match the content in 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.