有時候需要獲取進程的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
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)))
phoemur ~/python $ ./pgrep.py bash 1487 : -bash 1779 : /bin/bash
4,獲取當前腳本的pid進程
import os os.getpid()
