欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python使用標(biāo)準(zhǔn)庫根據(jù)進(jìn)程名如何獲取進(jìn)程的pid詳解

 更新時(shí)間:2017年10月31日 11:33:29   作者:那個(gè)踩到香蕉皮的妖怪  
Python有一套很有用的標(biāo)準(zhǔn)庫(standard library)。標(biāo)準(zhǔn)庫會(huì)隨著Python解釋器,一起安裝在你的電腦中的,所以下面這篇文章主要給大家介紹了關(guān)于python使用標(biāo)準(zhǔn)庫根據(jù)進(jìn)程名如何獲取進(jìn)程pid的相關(guān)資料,需要的朋友可以參考下。

前言

標(biāo)準(zhǔn)庫是Python的一個(gè)組成部分。這些標(biāo)準(zhǔn)庫是Python為你準(zhǔn)備好的利器,可以讓編程事半功倍。特別是有時(shí)候需要獲取進(jìn)程的pid,但又無法使用第三方庫的時(shí)候。下面話不多說了,來一起看看詳細(xì)的介紹吧。

方法適用linux平臺(tái).

方法1

使用subprocess 的check_output函數(shù)執(zhí)行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獲取的結(jié)果與pidof獲得的結(jié)果稍有不同.pgrep的進(jìn)程id稍多幾個(gè).pgrep命令可以使適用subprocess的check_out函數(shù)執(zhí)行

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目錄下的文件.這個(gè)方法不需要啟動(dòng)一個(gè)shell,只需要讀取/proc目錄下的文件即可獲取到進(jìn)程信息.

#!/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,獲取當(dāng)前腳本的pid進(jìn)程

import os
 
os.getpid()

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。

相關(guān)文章

最新評論