当前位置: 首页 > 图灵资讯 > 行业资讯> Python如何判断程序是否运行

Python如何判断程序是否运行

来源:图灵python
时间: 2026-06-01 21:56:58

本文介绍了Python判断程序进程是否存在的方法,希望对学习Python的朋友有所帮助!

Python如何判断程序是否运行?

1、进程名

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

2、进程ID

importerrno
importos
importsys


defpid_exists(pid):
"""Checkwhetherpidexistsinthecurrentprocesstable.
UNIXonly.
"""
ifpid<0:
returnFalse
ifpid==0:
#Accordingto"man2kill"PID0referstoeveryprocess
#intheprocessgroupofthecallingprocess.
#oncertainstemsisavalidPIDbutwehavenoway
#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

Python教程推荐学习。