#-*- 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):
name = argv[1]
get_pid(name)
if __name__ == "__main__":
main(sys.argv)
代码说明:
1.import psutil 需要安装,用于获取linux下进程列表
process_list = psutil.get_process_list() #获取进程列表
2.import re: python处理正则的模块
regex = "pid=(\d+),\sname=\'" + name + "\'" #组成string类型的正则表达式
ini_regex = re.compile(regex)#初始化正则表达式
result = ini_regex.search(process_info)#正则表达式匹配
result.group(0):匹配到的整个字符串的内容
result.group(1):匹配第一个()中的内容