首页 > 代码库 > 根据进程名称获取进程id
根据进程名称获取进程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