Advertisement
DigitalMag

procesman

Feb 1st, 2021
1,175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.21 KB | None | 0 0
  1. import subprocess
  2. import re
  3.  
  4. from sys import platform
  5.  
  6.  
  7. class proc_man:
  8.     os_commands = {
  9.         'get_proc_info': {
  10.             'win32': {
  11.                 'command': 'wmic process where description="{}.exe" get processid, Commandline /format:list',
  12.                 'splitter': '\n\n' * 2,
  13.             },
  14.             'linux': {
  15.                 'command': 'ps -fC {}',
  16.                 'splitter': '\n'
  17.             },
  18.             'darwin': None
  19.         }
  20.     }
  21.  
  22.     @classmethod
  23.     def get_process_by(cls, name='python'):
  24.         """
  25.        get processes by name for Windows
  26.        :param name:
  27.        :return:
  28.        """
  29.         # cmd = "wmic.exe path Win32_Process where description='python.exe' get Commandline /format:list"
  30.         # cmd = "wmic.exe path Win32_Process where handle='8828' get Commandline /format:htable"
  31.         # cmd = 'wmic process where description="python.exe" get processid, Commandline /format:list'
  32.         # ps = subprocess.check_output(cmd).split(b'\r\r\n\r\r\n')
  33.         cmd, sep = '', ''
  34.         cmd, sep = cls.os_commands.get('get_proc_info', {}).get(platform, 'linux').values()
  35.         ps = subprocess.getoutput(cmd.format(name)).split(sep)
  36.         ps_list = cls.get_proc_args(ps)
  37.  
  38.         # ps = [p.lstrip().split() for p in ps if p]
  39.         # args = [''.join(ps[1][1:-1]) for p in ps]
  40.         return [ps[1:-1] for ps in ps_list]
  41.  
  42.     @classmethod
  43.     def get_proc_args(cls, ps):
  44.         if platform.startswith('win'):
  45.             ps = [str(p.lstrip()) for p in ps if p.strip()]
  46.             ps_list = []
  47.             pos = 0
  48.             for p in ps:
  49.                 args_list = []
  50.                 files = re.finditer('"[\s\S]*"', p)
  51.                 for file in files:
  52.                     args_list.extend(p[pos:file.start()].split())
  53.                     args_list.append(file.group())  # .replace('\\\\', '\\')
  54.                     pos = file.end()
  55.                 args_list.extend(p[pos:].split())
  56.                 ps_list.append(args_list)
  57.             return ps_list
  58.         elif platform.startswith('linux'):
  59.             headers = len(ps[0].split())
  60.             args = [p.split()[headers - 1:] + ['ProcessId=' + p.split()[1]] for p in ps[1:]]
  61.             return args
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement