當前位置: 首頁>>代碼示例>>Python>>正文


Python psutil.pid_exists方法代碼示例

本文整理匯總了Python中psutil.pid_exists方法的典型用法代碼示例。如果您正苦於以下問題:Python psutil.pid_exists方法的具體用法?Python psutil.pid_exists怎麽用?Python psutil.pid_exists使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在psutil的用法示例。


在下文中一共展示了psutil.pid_exists方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: test_issue_687

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import pid_exists [as 別名]
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() 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:19,代碼來源:test_linux.py

示例2: get_process_ids

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import pid_exists [as 別名]
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 
開發者ID:google,項目名稱:clusterfuzz,代碼行數:24,代碼來源:utils.py

示例3: test_issue_687

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import pid_exists [as 別名]
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() 
開發者ID:giampaolo,項目名稱:psutil,代碼行數:21,代碼來源:test_linux.py

示例4: test_start_and_terminate

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import pid_exists [as 別名]
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()) 
開發者ID:apache,項目名稱:airflow,代碼行數:26,代碼來源:test_standard_task_runner.py

示例5: test_start_and_terminate_run_as_user

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import pid_exists [as 別名]
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()) 
開發者ID:apache,項目名稱:airflow,代碼行數:27,代碼來源:test_standard_task_runner.py

示例6: on_ready

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import pid_exists [as 別名]
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) 
開發者ID:DeadBread76,項目名稱:Raid-Toolbox,代碼行數:21,代碼來源:vcspam.py

示例7: get_all_dlls_by_process_pid

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import pid_exists [as 別名]
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.") 
開發者ID:Josue87,項目名稱:BoomER,代碼行數:21,代碼來源:list_dll_by_pid.py

示例8: _launch_qt_console

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import pid_exists [as 別名]
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() 
開發者ID:pyxll,項目名稱:pyxll-examples,代碼行數:23,代碼來源:ipython.py

示例9: _launch_qt_console

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import pid_exists [as 別名]
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() 
開發者ID:pyxll,項目名稱:pyxll-examples,代碼行數:23,代碼來源:ipython.py

示例10: run_next_workflow_in_queue

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import pid_exists [as 別名]
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 
開發者ID:vatlab,項目名稱:sos-notebook,代碼行數:22,代碼來源:workflow_executor.py

示例11: cancel_workflow

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import pid_exists [as 別名]
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 
開發者ID:vatlab,項目名稱:sos-notebook,代碼行數:21,代碼來源:workflow_executor.py

示例12: _read_pidfile

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import pid_exists [as 別名]
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 
開發者ID:jnrbsn,項目名稱:daemonocle,代碼行數:25,代碼來源:core.py

示例13: status_instance

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import pid_exists [as 別名]
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() 
開發者ID:MetPX,項目名稱:sarracenia,代碼行數:21,代碼來源:sr_instances.py

示例14: test_reap_process_tree_plain

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import pid_exists [as 別名]
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) 
開發者ID:botify-labs,項目名稱:simpleflow,代碼行數:20,代碼來源:test_base.py

示例15: test_reap_process_tree_children

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import pid_exists [as 別名]
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) 
開發者ID:botify-labs,項目名稱:simpleflow,代碼行數:22,代碼來源:test_base.py


注:本文中的psutil.pid_exists方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。