根据进程名称获取进程id
# -*- conding:utf-8-*-
import subprocess
def getpid_windows(process_name):
"""利用cmd_str = tasklist|find /i "xdict.exe" 来查找windows平台的进程id"""
cmd_line = 'tasklist|find /i "%s"' %process_name
pp = subprocess.Popen(cmd_line,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
out,err = pp.communicate()
if pp.returncode != 0:
print 'error:'+err
return -1
elif out.strip == '': # 这个情况是针对查询的进程没有启动的情况
print 'error:find process does not srart'
return -1
else:
out_str = out.strip()
print
pid = out_str[30:34]
return int(pid)
def getpid_linux(process_name):
"""利用 ps -ef|grep %s|grep -v grep|awk '{print $2}' 来查找linux 平台的进程id"""
cmd_line = "ps -ef|grep %s|grep -v grep|awk '{print $2}'" %process_name
pp = subprocess.Popen(cmd_line,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
out,err = pp.communicate()
if pp.returncode != 0:
print 'error:'+err
return -1
elif out.strip() == "":
print 'error:find process does not srart'
return -1
else:
pid = out.strip()
return int(pid)
if __name__ == '__main__':
name = 'XDict.exe'
pid = getpid_windows(name)
print pid
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步