python使用標(biāo)準(zhǔn)庫根據(jù)進(jìn)程名如何獲取進(jìn)程的pid詳解
前言
標(biāo)準(zhǔn)庫是Python的一個組成部分。這些標(biāo)準(zhǔn)庫是Python為你準(zhǔn)備好的利器,可以讓編程事半功倍。特別是有時候需要獲取進(jìn)程的pid,但又無法使用第三方庫的時候。下面話不多說了,來一起看看詳細(xì)的介紹吧。
方法適用linux平臺.
方法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稍多幾個.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目錄下的文件.這個方法不需要啟動一個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í)價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
Python?threading和Thread模塊及線程的實現(xiàn)
這篇文章主要介紹了Python?threading和Thread模塊及線程的實現(xiàn),Python通過兩個標(biāo)準(zhǔn)庫thread和threading提供對線程的支持,threading對thread進(jìn)行了封裝,具體實現(xiàn)介紹需要的朋友可以參考一下下面文章內(nèi)容2022-06-06
使用 python pyautogui實現(xiàn)鼠標(biāo)鍵盤控制功能
pyautogui是一個可以控制鼠標(biāo)和鍵盤的python庫,類似的還有pywin32。這篇文章主要介紹了python中的pyautogui實現(xiàn)鼠標(biāo)鍵盤控制功能,需要的朋友可以參考下2019-08-08
Python開啟Http Server的實現(xiàn)步驟
本文主要介紹了Python開啟Http Server的實現(xiàn)步驟,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07
如何在?ASP.NET?Core?中創(chuàng)建?gRPC?客戶端和服務(wù)器
gRPC 是一種高性能、開源的遠(yuǎn)程過程調(diào)用(RPC)框架,它基于 Protocol Buffers(protobuf)定義服務(wù),并使用 HTTP/2 協(xié)議進(jìn)行通信,這篇文章主要介紹了在?ASP.NET?Core?中創(chuàng)建?gRPC?客戶端和服務(wù)器,需要的朋友可以參考下2024-11-11
python安裝virtualenv虛擬環(huán)境步驟圖文詳解
這篇文章主要介紹了python安裝virtualenv虛擬環(huán)境步驟,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),具有一定的參考借鑒價值,需要的朋友可以參考下2019-09-09

