黑松山资源网 Design By www.paidiu.com
前言
标准库是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()
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。
黑松山资源网 Design By www.paidiu.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
黑松山资源网 Design By www.paidiu.com
暂无评论...
更新日志
2024年10月09日
2024年10月09日
- 【原神】V5.0攻略 | 林尼攻略一图流
- 李翊君.1993-相思的烈酒【上华】【WAV+CUE】
- 古巨基.1998-LEO.KU(国)【千禧年代】【WAV+CUE】
- 郭子.2001-原来你什么都不想要创作集丫滚石】【WAV+CUE】
- 《使命召唤:黑色行动6》新预告公布!10月25日发售
- Atlus《暗喻幻想》媒体评分汇总:高分好评如潮!
- 2024金摇杆奖提名揭晓 《黑神话》角逐最佳视觉设计!
- 群星《新说唱2024 第3期 (上)》[320K/MP3][32.76MB]
- 群星《新说唱2024 第3期 (上)》[FLAC/分轨][95.38MB]
- 群星《新说唱2024 第3期 (下)》[320K/MP3][31.36MB]
- 幻兽帕鲁手游什么时候正式上线 最新消息一览
- 西普大陆BOSS位置盘点 解锁天启纪元玩法
- 西普大陆精灵进阶培养攻略 精灵养成指南
- dnf手游法控法系职业哪个强 dnf手游法控法系职业强度排行
- 魔兽世界血藤护目镜图纸在哪买 wlk血藤护目镜图纸购买位置介绍