当前位置: 首页>>代码示例>>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;未经允许,请勿转载。