python3怎么判断进程是否存在

图片[1]-python3怎么判断进程是否存在-uusu优素-乐高,模型,3d打印,编程

通过进程名判断

importpsutil

defjudgeprocess(processname):
pl=psutil.pids()
forpidinpl:
ifpsutil.Process(pid).name()==processname:
print(pid)
break
else:
print("notfound")

ifjudgeprocess('notepad++.exe')==0:
print('success')
else:
pass

通过进程ID判断

importerrno
importos
importsys



defpid_exists(pid):
"""Checkwhetherpidexistsinthecurrentprocesstable.
UNIXonly.
"""
ifpid<0:
returnFalse
ifpid==0:
#Accordingto"man2kill"PID0referstoeveryprocess
#intheprocessgroupofthecallingprocess.
#Oncertainsystems0isavalidPIDbutwehavenoway
#toknowthatinaportablefashion.
raiseValueError('invalidPID0')
try:
os.kill(pid,0)
exceptOSErroraserr:
iferr.errno==errno.ESRCH:
#ESRCH==Nosuchprocess
returnFalse
eliferr.errno==errno.EPERM:
#EPERMclearlymeansthere'saprocesstodenyaccessto
returnTrue
else:
#Accordingto"man2kill"possibleerrorvaluesare
#(EINVAL,EPERM,ESRCH)
raise
else:
returnTrue
原文来自:https://www.py.cn
© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容