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


Python psutil.Error方法代碼示例

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


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

示例1: test_children_duplicates

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import Error [as 別名]
def test_children_duplicates(self):
        # find the process which has the highest number of children
        table = collections.defaultdict(int)
        for p in psutil.process_iter():
            try:
                table[p.ppid()] += 1
            except psutil.Error:
                pass
        # this is the one, now let's make sure there are no duplicates
        pid = sorted(table.items(), key=lambda x: x[1])[-1][0]
        p = psutil.Process(pid)
        try:
            c = p.children(recursive=True)
        except psutil.AccessDenied:  # windows
            pass
        else:
            self.assertEqual(len(c), len(set(c))) 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:19,代碼來源:test_process.py

示例2: test_children_duplicates

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import Error [as 別名]
def test_children_duplicates(self):
        # find the process which has the highest number of children
        table = collections.defaultdict(int)
        for p in psutil.process_iter():
            try:
                table[p.ppid()] += 1
            except psutil.Error:
                pass
        # this is the one, now let's make sure there are no duplicates
        pid = sorted(table.items(), key=lambda x: x[1])[-1][0]
        if LINUX and pid == 0:
            raise self.skipTest("PID 0")
        p = psutil.Process(pid)
        try:
            c = p.children(recursive=True)
        except psutil.AccessDenied:  # windows
            pass
        else:
            self.assertEqual(len(c), len(set(c))) 
開發者ID:giampaolo,項目名稱:psutil,代碼行數:21,代碼來源:test_process.py

示例3: kill_all_child_processes

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import Error [as 別名]
def kill_all_child_processes(pid=None):
    # get current process if pid not provided
    include_parent = True
    if not pid:
        pid = os.getpid()
        include_parent = False
    print("\nLeaving process id {}".format(pid))
    try:
        parent = psutil.Process(pid)
    except psutil.Error:
        # could not find parent process id
        return
    for child in parent.children(recursive=True):
        child.kill()
    if include_parent:
        parent.kill() 
開發者ID:allegroai,項目名稱:trains-agent,代碼行數:18,代碼來源:process.py

示例4: up

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import Error [as 別名]
def up(cluster_config_file, min_workers, max_workers, no_restart, restart_only,
       yes, cluster_name):
    """Create or update a Ray cluster."""
    if restart_only or no_restart:
        assert restart_only != no_restart, "Cannot set both 'restart_only' " \
            "and 'no_restart' at the same time!"
    if urllib.parse.urlparse(cluster_config_file).scheme in ("http", "https"):
        try:
            response = urllib.request.urlopen(cluster_config_file, timeout=5)
            content = response.read()
            file_name = cluster_config_file.split("/")[-1]
            with open(file_name, "wb") as f:
                f.write(content)
            cluster_config_file = file_name
        except urllib.error.HTTPError as e:
            logger.info("Error downloading file: ", e)
    create_or_update_cluster(cluster_config_file, min_workers, max_workers,
                             no_restart, restart_only, yes, cluster_name) 
開發者ID:ray-project,項目名稱:ray,代碼行數:20,代碼來源:scripts.py

示例5: _kill_all_child_processes

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import Error [as 別名]
def _kill_all_child_processes(send_kill=False):
        # get current process if pid not provided
        pid = os.getpid()
        try:
            parent = psutil.Process(pid)
        except psutil.Error:
            # could not find parent process id
            return
        for child in parent.children(recursive=True):
            if send_kill:
                child.kill()
            else:
                child.terminate()
        # kill ourselves
        if send_kill:
            parent.kill()
        else:
            parent.terminate() 
開發者ID:allegroai,項目名稱:trains,代碼行數:20,代碼來源:task.py

示例6: terminate

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import Error [as 別名]
def terminate(self):
        # return codes:
        # 0   no work to do
        # 1   terminated
        # -1  failed to terminate

        if not self.pid or not self.isrunning():
            return 0

        timeout = 20

        try:
            proc = psutil.Process(self.pid)
            proc.terminate()
            try:
                proc.wait(timeout=timeout/2)
            except psutil.TimeoutExpired:
                proc.kill()
                proc.wait(timeout=timeout/2)
        except psutil.Error:
            return -1

        return 1 
開發者ID:pytest-dev,項目名稱:pytest-xprocess,代碼行數:25,代碼來源:xprocess.py

示例7: _kill_process

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import Error [as 別名]
def _kill_process(self):
        with self._lock:
            if self._process is not None and self._process.is_running() and not self._process_children:
                try:
                    self._process.suspend()  # Suspend the process before getting list of childrens
                except psutil.Error as e:
                    logger.info('Failed to suspend the process: %s', e.msg)

                try:
                    self._process_children = self._process.children(recursive=True)
                except psutil.Error:
                    pass

                try:
                    self._process.kill()
                    logger.warning('Killed %s because it was still running', self._process_cmd)
                except psutil.NoSuchProcess:
                    pass
                except psutil.AccessDenied as e:
                    logger.warning('Failed to kill the process: %s', e.msg) 
開發者ID:zalando,項目名稱:patroni,代碼行數:22,代碼來源:cancellable.py

示例8: test_callback_executor

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import Error [as 別名]
def test_callback_executor(self, mock_popen):
        mock_popen.return_value.children.return_value = []
        mock_popen.return_value.is_running.return_value = True

        ce = CallbackExecutor()
        ce._kill_children = Mock(side_effect=Exception)
        self.assertIsNone(ce.call([]))
        ce.join()

        self.assertIsNone(ce.call([]))

        mock_popen.return_value.kill.side_effect = psutil.AccessDenied()
        self.assertIsNone(ce.call([]))

        ce._process_children = []
        mock_popen.return_value.children.side_effect = psutil.Error()
        mock_popen.return_value.kill.side_effect = psutil.NoSuchProcess(123)
        self.assertIsNone(ce.call([]))

        mock_popen.side_effect = Exception
        ce = CallbackExecutor()
        ce._condition.wait = Mock(side_effect=[None, Exception])
        self.assertIsNone(ce.call([]))
        ce.join() 
開發者ID:zalando,項目名稱:patroni,代碼行數:26,代碼來源:test_callback_executor.py

示例9: test_signal_kill

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import Error [as 別名]
def test_signal_kill(self, mock_kill, mock_children, mock_suspend):
        proc = PostmasterProcess(123)

        # all processes successfully stopped
        mock_children.return_value = [Mock()]
        mock_children.return_value[0].kill.side_effect = psutil.Error
        self.assertTrue(proc.signal_kill())

        # postmaster has gone before suspend
        mock_suspend.side_effect = psutil.NoSuchProcess(123)
        self.assertTrue(proc.signal_kill())

        # postmaster has gone before we got a list of children
        mock_suspend.side_effect = psutil.Error()
        mock_children.side_effect = psutil.NoSuchProcess(123)
        self.assertTrue(proc.signal_kill())

        # postmaster has gone after we got a list of children
        mock_children.side_effect = psutil.Error()
        mock_kill.side_effect = psutil.NoSuchProcess(123)
        self.assertTrue(proc.signal_kill())

        # failed to kill postmaster
        mock_kill.side_effect = psutil.AccessDenied(123)
        self.assertFalse(proc.signal_kill()) 
開發者ID:zalando,項目名稱:patroni,代碼行數:27,代碼來源:test_postmaster.py

示例10: _get_field

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import Error [as 別名]
def _get_field(self, field_name):
        try:
            result = getattr(self._proc, field_name)
            if callable(result):
                result = result()

            return result
        except psutil.Error:
            # Some processes do not have environ defined.
            if field_name == "environ":
                return {}

            return None
        except AttributeError:
            return None 
開發者ID:google,項目名稱:rekall,代碼行數:17,代碼來源:processes.py

示例11: discord_process

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import Error [as 別名]
def discord_process():
    executables = {}
    for proc in psutil.process_iter():
        try:
            (path, exe) = os.path.split(proc.exe())
        except (psutil.Error, OSError):
            pass
        else:
            if exe.startswith('Discord') and not exe.endswith('Helper'):
                entry = executables.get(exe)

                if entry is None:
                    entry = executables[exe] = DiscordProcess(path=path, exe=exe)

                entry.processes.append(proc)

    if len(executables) == 0:
        raise RuntimeError('Could not find Discord executable.')

    if len(executables) == 1:
        r = executables.popitem()
        print('Found {0.exe} under {0.path}'.format(r[1]))
        return r[1]

    lookup = list(executables)
    for index, exe in enumerate(lookup):
        print('%s: Found %s' % (index, exe))

    while True:
        index = input("Discord executable to use (number): ")
        try:
            index = int(index)
        except ValueError as e:
            print('Invalid index passed')
        else:
            if index >= len(lookup) or index < 0:
                print('Index too big (or small)')
            else:
                key = lookup[index]
                return executables[key] 
開發者ID:leovoel,項目名稱:BeautifulDiscord,代碼行數:42,代碼來源:app.py

示例12: test_exe

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import Error [as 別名]
def test_exe(self):
        for p in psutil.process_iter():
            try:
                self.assertEqual(os.path.basename(p.exe()), p.name())
            except psutil.Error:
                pass 
開發者ID:birforce,項目名稱:vnpy_crypto,代碼行數:8,代碼來源:test_windows.py

示例13: run

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import Error [as 別名]
def run(self):
        '''
        Runs until no longer valid (app moved, not master, etc), or repeated errors over self.threshold
        '''
        while self._run:
            start_time = time.time()
            if self.failcount >= self.threshold:
                self.logger.error('Node stat reporter thread for Monaco DB is sleeping to prevent thrashing')
                time.sleep(15)

            # Collect/Publish stats
            try:
                info = self.r.info()
                for stat in ['connected_slaves', 'used_memory', 'connected_clients', 'instantaneous_ops_per_sec']:
                    PUBLISHER.publish_monaco_stat(self.node_id, stat, info[stat])

                proc = self.redmgr.instance_proc('6379')
                if proc:
                    PUBLISHER.publish_monaco_stat(self.node_id, 'cpu_percent', proc.cpu_percent(interval=self.interval))

            except redis.ConnectionError:
                self.logger.info('Redis error accessing Monaco DB info')
                del self.r
                self.r = redis.StrictRedis(port=config.config['mgmt_port'])

            except psutil.Error, err:
                self.logger.info('psutil error - %s', repr(err))
                self.failcount += 1

            except Exception, exc:
                self.logger.exception(exc)
                self.failcount += 1 
開發者ID:hulu,項目名稱:monaco,代碼行數:34,代碼來源:monaco_stats.py

示例14: proc_info

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import Error [as 別名]
def proc_info(pid):
    tcase = PsutilTestCase()

    def check_exception(exc, proc, name, ppid):
        tcase.assertEqual(exc.pid, pid)
        tcase.assertEqual(exc.name, name)
        if isinstance(exc, psutil.ZombieProcess):
            if exc.ppid is not None:
                tcase.assertGreaterEqual(exc.ppid, 0)
                tcase.assertEqual(exc.ppid, ppid)
        elif isinstance(exc, psutil.NoSuchProcess):
            tcase.assertProcessGone(proc)
        str(exc)
        assert exc.msg

    def do_wait():
        if pid != 0:
            try:
                proc.wait(0)
            except psutil.Error as exc:
                check_exception(exc, proc, name, ppid)

    try:
        proc = psutil.Process(pid)
        d = proc.as_dict(['ppid', 'name'])
    except psutil.NoSuchProcess:
        return {}

    name, ppid = d['name'], d['ppid']
    info = {'pid': proc.pid}
    ns = process_namespace(proc)
    with proc.oneshot():
        for fun, fun_name in ns.iter(ns.getters, clear_cache=False):
            try:
                info[fun_name] = fun()
            except psutil.Error as exc:
                check_exception(exc, proc, name, ppid)
                continue
        do_wait()
    return info 
開發者ID:giampaolo,項目名稱:psutil,代碼行數:42,代碼來源:test_contracts.py

示例15: print_tree

# 需要導入模塊: import psutil [as 別名]
# 或者: from psutil import Error [as 別名]
def print_tree(parent, tree, indent=''):
    try:
        name = psutil.Process(parent).name()
    except psutil.Error:
        name = "?"
    print(parent, name)
    if parent not in tree:
        return
    children = tree[parent][:-1]
    for child in children:
        sys.stdout.write(indent + "|- ")
        print_tree(child, tree, indent + "| ")
    child = tree[parent][-1]
    sys.stdout.write(indent + "`_ ")
    print_tree(child, tree, indent + "  ") 
開發者ID:giampaolo,項目名稱:psutil,代碼行數:17,代碼來源:pstree.py


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