python 获取进程的pid

2021-12-16  本文已影响0人  逍遥_yjz

方法一:
使用subprocess 的check_output函数执行pidof命令

from subprocess import check_output
def get_pid(name):
    return list(map(int,check_output(["pidof",name]).split()))

if __name__ == '__main__':

    print(get_pid('python'))

方法二:

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


import subprocess

def get_process_id(name):
    child = subprocess.Popen(['pgrep', '-f', name], stdout=subprocess.PIPE, shell=False)
    response = child.communicate()[0]
    return [int(pid) for pid in response.split()]

# 启动命令和参数,空格

方法三:
获取当前脚本的pid进程

import os
os.getpid()

方法四:命令获取+kill PID

ps -ef | grep firefox | grep -v grep | cut -c 9-15 | xargs kill -s 9

说明:

注意:linux的进程号最大是是 32768 (32 位系统)和 2 的 22 次方(400w 左右)(64 位系统)。cut -c 9-15不够,改成awk '{print $2}'

上一篇 下一篇

猜你喜欢

热点阅读