python如何获取进程pid号?
例子,将以下代码保存为.py文件,在脚本后面添加进程名称即可运行,比如:python proinfo.py qq 即可获取QQ的进程信息,注意不区分大小写。
#!/usr/bin/python #-*- 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)
代码说明:
1,import psutil 需要安装,用于获取linux进程列表。www.jb200.com
2,import re: python处理正则的模块