# -*- 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

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-02-14
  • 2022-12-23
  • 2022-02-07
  • 2022-12-23
  • 2022-12-23
  • 2022-01-29
猜你喜欢
  • 2021-12-04
  • 2022-12-23
  • 2022-01-22
  • 2022-12-23
  • 2022-12-23
  • 2021-07-31
  • 2021-12-05
相关资源
相似解决方案