Method to get the pid number of the process using python
- 2020-04-02 13:28:23
- OfStack
Save as. Py file and run the script after adding the process name such as :python proinfo.py qq to get the qq process information, pay attention to case-insensitive
#-*- 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 get the list of processes under Linux
process_list = psutil.get_process_list() # Get the list of processes
2. Import re: python handles regular modules
regex = "pid=(d+),sname='" + name + "'" # composition string A regular expression of type
ini_regex = re.compile(regex)# Initializes the regular expression
result = ini_regex.search(process_info)# Regular expression matching
result.group(0): The contents of the entire string that matches
result.group(1): Match the first one () The contents of the