python使用标准库根据进程名如何获取进程的pid详解

yipeiwu_com5年前Python基础

前言

标准库是Python的一个组成部分。这些标准库是Python为你准备好的利器,可以让编程事半功倍。特别是有时候需要获取进程的pid,但又无法使用第三方库的时候。下面话不多说了,来一起看看详细的介绍吧。

方法适用linux平台.

方法1

使用subprocess 的check_output函数执行pidof命令

from subprocess import check_output
def get_pid(name):
 return map(int,check_output(["pidof",name]).split())
 
In [21]: get_pid("chrome")
Out[21]:
[27698, 27678, 27665, 27649, 27540, 27530,]

方法2

使用pgrep命令,pgrep获取的结果与pidof获得的结果稍有不同.pgrep的进程id稍多几个.pgrep命令可以使适用subprocess的check_out函数执行

import subprocess<br data-filtered="filtered">def get_process_id(name):
 """Return process ids found by (partial) name or regex.
 
 >>> get_process_id('kthreadd')
 [2]
 >>> get_process_id('watchdog')
 [10, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61] # ymmv
 >>> get_process_id('non-existent process')
 []
 """
 child = subprocess.Popen(['pgrep', '-f', name], stdout=subprocess.PIPE, shell=False)
 response = child.communicate()[0]
 return [int(pid) for pid in response.split()]

方法3

直接读取/proc目录下的文件.这个方法不需要启动一个shell,只需要读取/proc目录下的文件即可获取到进程信息.

#!/usr/bin/env python
 
import os
import sys
 
 
for dirname in os.listdir('/proc'):
 if dirname == 'curproc':
  continue
 
 try:
  with open('/proc/{}/cmdline'.format(dirname), mode='rb') as fd:
   content = fd.read().decode().split('\x00')
 except Exception:
  continue
 
 for i in sys.argv[1:]:
  if i in content[0]:
   print('{0:<12} : {1}'.format(dirname, ' '.join(content)))<br data-filtered="filtered"><br data-filtered="filtered">
phoemur ~/python $ ./pgrep.py bash
1487   : -bash 
1779   : /bin/bash

4,获取当前脚本的pid进程

import os
 
os.getpid()

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对【听图阁-专注于Python设计】的支持。

相关文章

详解Matplotlib绘图之属性设置

详解Matplotlib绘图之属性设置

关于Python数据分析在数学建模中的更多相关应用:Python数据分析在数学建模中的应用汇总(持续更新中!) (1)、导入库 import matplotlib.pyplot a...

numpy linalg模块的具体使用方法

最近在看机器学习的 LogisticRegressor,BayesianLogisticRegressor算法,里面得到一阶导数矩阵g和二阶导数Hessian矩阵H的时候,用到...

Python读取excel中的图片完美解决方法

Python读取excel中的图片完美解决方法

excel中有图片是很常见的,但是通过python读取excel中的图片没有很好的解决办法。 网上找了一种很聪明的方法,原理是这样的: 1、将待读取的excel文件后缀名改成zip,变成...

python 统计数组中元素出现次数并进行排序的实例

如下所示: lis = [12,34,456,12,34,66,223,12,5,66,12,23,66,12,66,5,456,12,66,34,5,34] def test1(...

详解python中的线程

Python中创建线程有两种方式:函数或者用类来创建线程对象。 函数式:调用 _thread 模块中的start_new_thread()函数来产生新线程。 类:创建threading...