Python psutil.pid_exists() Examples

The following are 30 code examples of psutil.pid_exists(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module psutil , or try the search function .
Example #1
Source File: vcspam.py    From Raid-Toolbox with GNU General Public License v2.0 6 votes vote down vote up
def on_ready():
    await asyncio.sleep(1)
    voice_channel = client.get_channel(int(voice_id))
    while not client.is_closed():
        vc = await voice_channel.connect()
        vc.play(discord.FFmpegPCMAudio(filename))
        vc.source = discord.PCMVolumeTransformer(vc.source)
        vc.source.volume = 10.0
        while vc.is_playing():
            if sys.platform.startswith('linux'):
                proc = psutil.Process(int(parentprocess))
                if proc.status() == psutil.STATUS_ZOMBIE:
                    await client.logout()
                    sys.exit()
            if not psutil.pid_exists(int(parentprocess)):  # Parent is dead, Kill self :cry:
                await client.logout()
                sys.exit()
            await asyncio.sleep(0.5)
        await vc.disconnect(force=True) 
Example #2
Source File: sr_instances.py    From sarracenia with GNU General Public License v2.0 6 votes vote down vote up
def status_instance(self,sanity=False):
        if self.pid == None :
           if not sanity : self.logger.info("%s is stopped" % self.instance_str)
           return

        if psutil.pid_exists(self.pid):
             p = psutil.Process(self.pid)
             status = p.status
             if not isinstance(p.status,str): status = p.status()
             status = status.lower()
             status = status.replace('sleeping','running')
             if not sanity : self.logger.info("%s is %s (pid=%d)" % (self.instance_str,status,self.pid))
             return
        else:
             self.logger.info("%s instance missing (pid=%d)" % (self.instance_str, self.pid) )

        if sanity :
           self.logger.info("%s restart" % self.instance_str)
           self.restart_instance() 
Example #3
Source File: system.py    From choochoo with GNU General Public License v2.0 6 votes vote down vote up
def exists(pid, time, delta_seconds=3, zombie_seconds=10):
    if not ps.pid_exists(pid):
        log.debug(f'Process {pid} does not exist')
        return False
    process = ps.Process(pid)
    if process.status() == ps.STATUS_ZOMBIE:
        try:
            log.warning(f'Waiting for zombie {pid}')
            process.wait(zombie_seconds)
        except ps.TimeoutExpired:
            log.debug(f'Timeout waiting for zombie {pid}')
        return False
    elif delta_seconds:
        creation_ok = abs(process.create_time() - time.timestamp()) < delta_seconds
        if creation_ok:
            log.debug(f'Process {pid} still exists')
        else:
            log.debug(f'Creation time for process {pid} incorrect ({process.create_time()} / {time.timestamp()})')
        return creation_ok
    else:
        log.debug(f'Assuming process {pid} is same as expected')
        return True   # if delta_seconds = 0 don't check, just assume same 
Example #4
Source File: test_base.py    From simpleflow with MIT License 6 votes vote down vote up
def test_reap_process_tree_plain(handler):
    """
    Tests that process is killed when handling SIGTERM, times out, or ignores.
    """
    proc = Process(target=noop_target, args=[handler])
    try:
        proc.start()
        # Wait until ready
        while not proc.pid:
            time.sleep(0.1)
        assert psutil.pid_exists(proc.pid)
        base.reap_process_tree(proc.pid, wait_timeout=0.1)
        assert not psutil.pid_exists(proc.pid)
    finally:
        # Clean up any potentially danging processp
        if psutil.pid_exists(proc.pid):
            os.kill(proc.pid, signal.SIGKILL)
            assert False, 'KILLed process with pid={}'.format(proc.pid) 
Example #5
Source File: test_base.py    From simpleflow with MIT License 6 votes vote down vote up
def test_reap_process_tree_children(handler):
    """
    Tests recursive termination children with SIGTERM handlers.
    """
    child_pid = Value('i', 0)
    lock = Lock()
    proc = Process(target=nested_target, args=[handler, child_pid, lock])
    try:
        proc.start()
        while not proc.pid or not child_pid.value:
            time.sleep(0.1)
        pids = [proc.pid, child_pid.value]
        assert all(psutil.pid_exists(p) for p in pids)
        base.reap_process_tree(proc.pid, wait_timeout=1)
        assert all(not psutil.pid_exists(p) for p in pids)
    finally:
        for pid in pids:
            if psutil.pid_exists(proc.pid):
                os.kill(proc.pid, signal.SIGKILL)
                assert False, 'KILLed process with pid={}'.format(proc.pid) 
Example #6
Source File: test_linux.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def test_issue_687(self):
        # In case of thread ID:
        # - pid_exists() is supposed to return False
        # - Process(tid) is supposed to work
        # - pids() should not return the TID
        # See: https://github.com/giampaolo/psutil/issues/687
        t = ThreadTask()
        t.start()
        try:
            p = psutil.Process()
            tid = p.threads()[1].id
            assert not psutil.pid_exists(tid), tid
            pt = psutil.Process(tid)
            pt.as_dict()
            self.assertNotIn(tid, psutil.pids())
        finally:
            t.stop() 
Example #7
Source File: engine.py    From equant with GNU General Public License v2.0 6 votes vote down vote up
def run(self):
        # 在当前进程中初始化
        self._initialize()

        while True:
            try:
                self._handleUIData()

                ppid = os.getppid()
                if ppid == 1 or not psutil.pid_exists(ppid):
                    self.saveStrategyContext2File()
                    os._exit(0)

            except Exception as e:
                errorText = traceback.format_exc()
                self.sendErrorMsg(-1, errorText) 
Example #8
Source File: core.py    From daemonocle with MIT License 6 votes vote down vote up
def _read_pidfile(self):
        """Read the PID file and check to make sure it's not stale."""
        if self.pidfile is None:
            return None

        if not os.path.isfile(self.pidfile):
            return None

        # Read the PID file
        with open(self.pidfile, 'r') as fp:
            try:
                pid = int(fp.read())
            except ValueError:
                self._emit_warning('Empty or broken pidfile {pidfile}; '
                                   'removing'.format(pidfile=self.pidfile))
                pid = None

        if pid is not None and psutil.pid_exists(pid):
            return pid
        else:
            # Remove the stale PID file
            os.remove(self.pidfile)
            return None 
Example #9
Source File: utils.py    From clusterfuzz with Apache License 2.0 6 votes vote down vote up
def get_process_ids(process_id, recursive=True):
  """Return list of pids for a process and its descendants."""
  # Try to find the running process.
  if not psutil.pid_exists(process_id):
    return []

  pids = [process_id]

  try:
    psutil_handle = psutil.Process(process_id)
    children = psutil_handle.children(recursive=recursive)
    for child in children:
      pids.append(child.pid)
  except psutil.NoSuchProcess:
    # Avoid too much logging when the process already died.
    return []

  except (psutil.AccessDenied, OSError):
    logs.log_warn('Failed to get process children.')
    return []

  return pids 
Example #10
Source File: workflow_executor.py    From sos-notebook with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def cancel_workflow(cell_id, kernel):
    global g_workflow_queue
    env.logger.info(f'A queued or running workflow in this cell is canceled')
    kernel.send_frontend_msg('workflow_status', {
        'cell_id': cell_id,
        'status': 'purged'
    })

    for idx, (cid, proc) in enumerate(g_workflow_queue):
        if cid != cell_id or proc is None:
            continue
        if not isinstance(proc, tuple) and (proc.is_alive() and
                                            psutil.pid_exists(proc.pid)):
            from sos.executor_utils import kill_all_subprocesses
            kill_all_subprocesses(proc.pid, include_self=True)
            proc.terminate()
            if psutil.pid_exists(proc.pid):
                raise RuntimeError('Failed to kill workflow')
        g_workflow_queue[idx][1] = None 
Example #11
Source File: workflow_executor.py    From sos-notebook with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def run_next_workflow_in_queue():
    # execute the first available item
    global g_workflow_queue

    for idx, (cid, proc) in enumerate(g_workflow_queue):
        if proc is None:
            continue
        # this is ordered
        elif isinstance(proc, tuple):
            env.config['slave_id'] = cid
            executor = Tapped_Executor(*proc)
            executor.start()
            g_workflow_queue[idx][1] = executor
            break
        elif not (proc.is_alive() and psutil.pid_exists(proc.pid)):
            g_workflow_queue[idx][1] = None
            continue
        else:
            # if already running, do not submit new one
            break 
Example #12
Source File: test_linux.py    From psutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_issue_687(self):
        # In case of thread ID:
        # - pid_exists() is supposed to return False
        # - Process(tid) is supposed to work
        # - pids() should not return the TID
        # See: https://github.com/giampaolo/psutil/issues/687
        t = ThreadTask()
        t.start()
        try:
            p = psutil.Process()
            threads = p.threads()
            self.assertEqual(len(threads), 2)
            tid = sorted(threads, key=lambda x: x.id)[1].id
            self.assertNotEqual(p.pid, tid)
            pt = psutil.Process(tid)
            pt.as_dict()
            self.assertNotIn(tid, psutil.pids())
        finally:
            t.stop() 
Example #13
Source File: ipython.py    From pyxll-examples with The Unlicense 6 votes vote down vote up
def _launch_qt_console(ppid, connection_file):
    """called as a new process"""
    from IPython.frontend.terminal.ipapp import TerminalIPythonApp
    import threading
    import psutil
    import time
    
    # start a thread to kill this process when the parent process exits
    def thread_func():
        while True:
            if not psutil.pid_exists(ppid):
                os._exit(1)
            time.sleep(5)
    thread = threading.Thread(target=thread_func)
    thread.daemon = True
    thread.start()
    
    # start the qtconsole app
    app = TerminalIPythonApp.instance()
    app.initialize(["qtconsole", "--existing", connection_file])
    app.start() 
Example #14
Source File: ipython.py    From pyxll-examples with The Unlicense 6 votes vote down vote up
def _launch_qt_console(ppid, connection_file):
    """called as a new process"""
    from IPython.terminal.ipapp import TerminalIPythonApp
    import threading
    import psutil
    import time
    
    # start a thread to kill this process when the parent process exits
    def thread_func():
        while True:
            if not psutil.pid_exists(ppid):
                os._exit(1)
            time.sleep(5)
    thread = threading.Thread(target=thread_func)
    thread.daemon = True
    thread.start()
    
    # start the qtconsole app
    app = TerminalIPythonApp.instance()
    app.initialize(["qtconsole", "--existing", connection_file])
    app.start() 
Example #15
Source File: test_standard_task_runner.py    From airflow with Apache License 2.0 6 votes vote down vote up
def test_start_and_terminate(self):
        local_task_job = mock.Mock()
        local_task_job.task_instance = mock.MagicMock()
        local_task_job.task_instance.run_as_user = None
        local_task_job.task_instance.command_as_list.return_value = [
            'airflow', 'tasks', 'test', 'test_on_kill', 'task1', '2016-01-01'
        ]

        runner = StandardTaskRunner(local_task_job)
        runner.start()
        time.sleep(0.5)

        pgid = os.getpgid(runner.process.pid)
        self.assertGreater(pgid, 0)
        self.assertNotEqual(pgid, os.getpgid(0), "Task should be in a different process group to us")

        processes = list(self._procs_in_pgroup(pgid))

        runner.terminate()

        for process in processes:
            self.assertFalse(psutil.pid_exists(process.pid), "{} is still alive".format(process))

        self.assertIsNotNone(runner.return_code()) 
Example #16
Source File: test_standard_task_runner.py    From airflow with Apache License 2.0 6 votes vote down vote up
def test_start_and_terminate_run_as_user(self):
        local_task_job = mock.Mock()
        local_task_job.task_instance = mock.MagicMock()
        local_task_job.task_instance.run_as_user = getpass.getuser()
        local_task_job.task_instance.command_as_list.return_value = [
            'airflow', 'tasks', 'test', 'test_on_kill', 'task1', '2016-01-01'
        ]

        runner = StandardTaskRunner(local_task_job)

        runner.start()
        time.sleep(0.5)

        pgid = os.getpgid(runner.process.pid)
        self.assertGreater(pgid, 0)
        self.assertNotEqual(pgid, os.getpgid(0), "Task should be in a different process group to us")

        processes = list(self._procs_in_pgroup(pgid))

        runner.terminate()

        for process in processes:
            self.assertFalse(psutil.pid_exists(process.pid), "{} is still alive".format(process))

        self.assertIsNotNone(runner.return_code()) 
Example #17
Source File: list_dll_by_pid.py    From BoomER with GNU General Public License v3.0 6 votes vote down vote up
def get_all_dlls_by_process_pid(pid):
    try:
        if not psutil.pid_exists(pid):
            print('There is no process running with PID: ' + str(pid))
            # return;

        p = psutil.Process(pid)
        dll_list = []
        for dll in p.memory_maps():
            if(dll.path[-3:] == "dll"):
                # print("Service name: " + p.name() + "- path: " + dll.path)
                dll_list.append(dll.path)

        for dll in dll_list:
            if not os.path.isfile(dll):
                print(dll + 'doesnt exists!! - PID: ' + str(pid))
    except AccessDenied:
        pass
        # print("Access denied for this process.") 
Example #18
Source File: gpustat.py    From trains-agent with Apache License 2.0 5 votes vote down vote up
def clean_processes():
        for pid in list(GPUStatCollection.global_processes.keys()):
            if not psutil.pid_exists(pid):
                del GPUStatCollection.global_processes[pid] 
Example #19
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def is_running(pid):
            return psutil.pid_exists(pid) 
Example #20
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def is_running():
            try:
                if System.Ahenk.get_pid_number() is not None:
                    return psutil.pid_exists(int(System.Ahenk.get_pid_number()))
                else:
                    return False
            except Exception as e:
                return False 
Example #21
Source File: test_reusable_executor.py    From loky with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def check_pids_exist_then_sleep(arg):
    """Sleep for some time before returning
    and check if all the passed pid exist"""
    time, pids = arg
    sleep(time)
    res = True
    for p in pids:
        res &= psutil.pid_exists(p)
    return res 
Example #22
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def is_running(pid):
            return psutil.pid_exists(pid) 
Example #23
Source File: system.py    From ahenk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def is_running():
            try:
                if System.Ahenk.get_pid_number() is not None:
                    return psutil.pid_exists(int(System.Ahenk.get_pid_number()))
                else:
                    return False
            except Exception as e:
                return False 
Example #24
Source File: __init__.py    From platypush with MIT License 5 votes vote down vote up
def pid_exists(self, pid: int) -> bool:
        """
        :param pid: Process PID.
        :return: ``True`` if the process exists, ``False`` otherwise.
        """
        import psutil
        return psutil.pid_exists(pid) 
Example #25
Source File: indexq.py    From SolrClient with Apache License 2.0 5 votes vote down vote up
def _is_locked(self):
        '''
        Checks to see if we are already pulling items from the queue
        '''
        if os.path.isfile(self._lck):
            try:
                import psutil
            except ImportError:
                return True #Lock file exists and no psutil
            #If psutil is imported
            with open(self._lck) as f:
                pid = f.read()
            return True if psutil.pid_exists(int(pid)) else False
        else:
            return False 
Example #26
Source File: desktop.py    From parsec-cloud with GNU Affero General Public License v3.0 5 votes vote down vote up
def is_process_running(pid):
    return psutil.pid_exists(pid) 
Example #27
Source File: win_registry.py    From parsec-cloud with GNU Affero General Public License v3.0 5 votes vote down vote up
def cleanup_parsec_drive_icons():
    # Winreg is not available for some reasons
    if platform.system() != "Windows" or not try_winreg():
        return

    # Loop over the 26 drives
    for letter in string.ascii_uppercase:

        # Perform some cleanup if necessary
        _, pid = get_parsec_drive_icon(letter)
        if pid and not psutil.pid_exists(pid):
            del_parsec_drive_icon(letter) 
Example #28
Source File: cpu_gpu_profiler.py    From deeplearning-benchmark with Apache License 2.0 5 votes vote down vote up
def get_cpu_mem_usage_from_process(pid, cpu_usage):
    """Get CPU memory usage given process id, result append to a mutable list."""
    if not psutil.pid_exists(pid):
        return
    proc = psutil.Process(pid)
    if proc.is_running():
        # The rss, Resident Set Size, is the memory allocated to the process, its unit is KB.
        cpu_usage.append(proc.memory_info().rss / 1024) 
Example #29
Source File: test_kill_child_process.py    From whatsapp-play with MIT License 5 votes vote down vote up
def test_kill(self):
        sproc = test_func.get_test_subprocess()
        test_pid = sproc.pid
        p = psutil.Process(test_pid)
        kill_child_processes(test_pid)
        p.wait()
        self.assertFalse(psutil.pid_exists(test_pid)) 
Example #30
Source File: monitor_process.py    From pi-process-dashboard with MIT License 5 votes vote down vote up
def main():
	if len(sys.argv) != 2:
		print "Usage: " + sys.argv[0] + " <pid>"
		exit()
	pid = sys.argv[1]

	streamer = Streamer(bucket_name=BUCKET_NAME, bucket_key=BUCKET_KEY, access_key=ACCESS_KEY)
	if psutil.pid_exists(int(pid)) == False:
		print "Error: That process doesn't exist! Exiting ..."
		exit()
	else:
		streamer.log(PROCESS_NAME,"Running")
		streamer.flush()

	while True:
		if psutil.pid_exists(int(pid)) == False:
			streamer.log(PROCESS_NAME,"Exited")
			streamer.flush()
			exit()
		else:
			streamer.log(PROCESS_NAME,"Running")
			process = Popen(['hostname', '-I'], stdout=PIPE)
			output, _error = process.communicate()
			streamer.log(PROCESS_NAME + " IP Address", output.rstrip())
			streamer.flush()
		time.sleep(60*MINUTES_BETWEEN_READS)