Python psutil 模块,Process() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用psutil.Process()

项目:pykit    作者:baishancloud    | 项目源码 | 文件源码
def mem_check(opts):

    while True:

        if opts['gc']:
            try:
                gc.collect()
            except Exception as e:
                logging.exception(repr(e) + ' while gc.collect()')

        try:
            rss = psutil.Process(os.getpid()).memory_info().rss

            logging.info('current memory used: {rss}'.format(rss=rss))

            if rss > opts['threshold']:
                memory_dump(opts)
                os.abort()
        except Exception as e:
            logging.exception(repr(e) + ' while checking memory usage')

        finally:
            time.sleep(opts['interval'])
项目:Chasar    作者:camilochs    | 项目源码 | 文件源码
def pids_active(pids_computer):
    """
    This function find pids of computer and return the valid.
    """
    pid_valid = {}
    for pid in pids_computer:
        data = None
        try:
            process = psutil.Process(pid)
            data = {"pid": process.pid,
                    "status": process.status(),
                    "percent_cpu_used": process.cpu_percent(interval=0.0),
                    "percent_memory_used": process.memory_percent()}

        except (psutil.ZombieProcess, psutil.AccessDenied, psutil.NoSuchProcess):
            data = None

        if data is not None:
            pid_valid[process.name()] = data
    return pid_valid
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
def process_finished(self, exit_code):
        format = self.ui.edit_stdout.currentCharFormat()
        format.setFontWeight(QFont.Bold)
        if exit_code == 0:
            if self._interrupted:
                color = Qt.red
                msg = ('Process interrupted by user')
            else:
                color = Qt.green
                msg = ('Process exited normally')
        else:
            color = Qt.red
            msg = ('Process exited with exit code %d' % exit_code)
        format.setForeground(color)
        self.ui.edit_stdout.setCurrentCharFormat(format)
        self.ui.edit_stdout.appendPlainText(msg)
        self.restore_gui()
        self.ui.edit_stdout.setTextInteractionFlags(Qt.TextSelectableByMouse |
                                                    Qt.TextSelectableByKeyboard)
        self.process = None
        self.ui.btn_log.setEnabled(self.last_log_file is not None and
                                   os.path.isfile(self.last_log_file))
项目:data_pipeline    作者:Yelp    | 项目源码 | 文件源码
def set_zombie_refresh_to_fail(self, refresh_job):
        current_pid = refresh_job.pid
        if current_pid is None:
            return

        p = psutil.Process(current_pid)
        if p.status() != psutil.STATUS_ZOMBIE:
            return

        refresh = self.schematizer.get_refresh_by_id(
            refresh_job.refresh_id
        )
        if refresh.status == RefreshStatus.IN_PROGRESS:
            # Must update manually (not relying on the signal),
            # as the process may not properly handle the signal
            # if it's a zombie
            self.schematizer.update_refresh(
                refresh_id=refresh_job.refresh_id,
                status=RefreshStatus.FAILED,
                offset=0
            )
            source = refresh_job.source
            del self.active_refresh_jobs[source]
        os.kill(current_pid, signal.SIGINT)
项目:BioQueue    作者:liyao001    | 项目源码 | 文件源码
def kill_proc(proc):
    """
    Kill a process and its children processes
    :param proc: Process class defined in psutil
    :return: None
    """
    try:
        children = proc.children()
        for child in children:
            try:
                child.terminate()
            except:
                pass
        gone, still_alive = psutil.wait_procs(children, timeout=3)
        for p in still_alive:
            p.kill()
        proc.kill()
    except:
        pass
项目:respeaker_virtualenv    作者:respeaker    | 项目源码 | 文件源码
def test_procfs_path(self):
        tdir = tempfile.mkdtemp()
        try:
            psutil.PROCFS_PATH = tdir
            self.assertRaises(IOError, psutil.virtual_memory)
            self.assertRaises(IOError, psutil.cpu_times)
            self.assertRaises(IOError, psutil.cpu_times, percpu=True)
            self.assertRaises(IOError, psutil.boot_time)
            # self.assertRaises(IOError, psutil.pids)
            self.assertRaises(IOError, psutil.net_connections)
            self.assertRaises(IOError, psutil.net_io_counters)
            self.assertRaises(IOError, psutil.net_if_stats)
            self.assertRaises(IOError, psutil.disk_io_counters)
            self.assertRaises(IOError, psutil.disk_partitions)
            self.assertRaises(psutil.NoSuchProcess, psutil.Process)
        finally:
            psutil.PROCFS_PATH = "/proc"
            os.rmdir(tdir)
项目:cli    作者:sparkl    | 项目源码 | 文件源码
def get_default_session():
    """
    Locates the first ancestor process which is a shell. Returns
    its pid, or None if not found.
    """
    if psutil.POSIX:
        def predicate(name):
            return name.endswith("sh")

    elif psutil.WINDOWS:
        def predicate(name):
            return name in ("cmd.exe", "powershell.exe")

    else:
        return None

    proc = psutil.Process()
    while proc.parent().pid:
        proc = proc.parent()
        if predicate(proc.name()):
            return proc.pid

    return None
项目:rolld    作者:Hipo    | 项目源码 | 文件源码
def has_connection(processes):
    for i in processes:
        proc = psutil.Process(i.pid)
        conns = proc.connections()

        # find our listening port
        ports = set()
        for conn in conns:
            if conn.status == 'LISTEN':
                if conn.laddr:
                    ports.add(conn.laddr[1])

        for conn in conns:
            if conn.status == 'ESTABLISHED' and conn.laddr[1] in ports:
                print "conn ", conn
                return True
项目:Prism    作者:Stumblinbear    | 项目源码 | 文件源码
def restart(self):
        """ Safely restart prism """
        import os
        import sys
        import psutil
        import logging

        try:
            p = psutil.Process(os.getpid())
            for handler in p.open_files() + p.connections():
                os.close(handler.fd)
        except Exception as e:
            logging.error(e)

        python = sys.executable
        os.execl(python, python, *sys.argv)
项目:Dallinger    作者:Dallinger    | 项目源码 | 文件源码
def __repr__(self):
        classname = self.__class__.__name__
        if not self.is_running:
            return "<{} (not running)>".format(classname)

        reprs = []
        for child in psutil.Process(self._process.pid).children(recursive=True):
            if 'python' in child.name():
                name = ''.join(child.cmdline())
            else:
                name = child.name()
            reprs.append("<Process pid='{}', name='{}', status='{}'>".format(
                child.pid, name, child.status())
            )

        return "<{} pid='{}', children: {}>".format(
            classname, self._process.pid, reprs
        )
项目:brainiak    作者:brainiak    | 项目源码 | 文件源码
def usable_cpu_count():
    """Get number of CPUs usable by the current process.

    Takes into consideration cpusets restrictions.

    Returns
    -------
    int
    """
    try:
        result = len(os.sched_getaffinity(0))
    except AttributeError:
        try:
            result = len(psutil.Process().cpu_affinity())
        except AttributeError:
            result = os.cpu_count()
    return result
项目:HSISeg    作者:HSISeg    | 项目源码 | 文件源码
def kill_task(request):
    if request.method == 'POST':
        try:
            params = json.loads(request.body)
        except:
            return HttpResponseBadRequest(json.dumps({'error':'Json required'}),content_type="application/json")
        if not params.get("task_id"): 
            return HttpResponseBadRequest(json.dumps({'error':'task_id manadatory'}),content_type="application/json")
        tasks = Results.objects.filter(id = params['task_id'])
        for task in tasks:
            try:
                parent = psutil.Process(task.pid)
                for child in parent.children(recursive=True):
                    child.kill()
                parent.kill()
            except Exception as e:
                pass
            task.status_text = 'Killed'
            task.is_done = True
            task.save()
        return HttpResponse(json.dumps({'success':True}),content_type="application/json")
    else:
        raise Http404()
项目:raiden    作者:raiden-network    | 项目源码 | 文件源码
def wait_for_listening_port(port_number, tries=10, sleep=0.1, pid=None):
    if pid is None:
        pid = os.getpid()
    for _ in range(tries):
        gevent.sleep(sleep)
        # macoOS requires root access for the connections api to work
        # so get connections of the current process only
        connections = psutil.Process(pid).connections()
        for conn in connections:
            if conn.status == 'LISTEN' and conn.laddr[1] == port_number:
                return

    raise RuntimeError('{port} is not bound'.format(port=port_number))


# TODO: Figure out why this fixture can't work as session scoped
#       What happens is that after one test is done, in the next one
#       the server is no longer running even though the teardown has not
#       been invoked.
项目:flask-boilerplate    作者:MarcFord    | 项目源码 | 文件源码
def gulp_exited_cb(future):
        if future.exception():
            print(traceback.format_exc())

            children = psutil.Process().children(recursive=True)

            for child in children:
                print('>>> Killing pid {}'.format(child.pid))

                child.send_signal(SIGTERM)

            print('>>> Exiting')

            # It would be nice to be able to raise a CommandError or use
            # sys.kill here but neither of those stop the runserver instance
            # since we're in a thread. This method is used in django as well.
            os._exit(1)
项目:Chasar    作者:camilochs    | 项目源码 | 文件源码
def pids_active(pids_computer):
    """
    This function find pids of computer and return the valid.
    """
    pid_valid = {}
    for pid in pids_computer:
        data = None
        try:
            process = psutil.Process(pid)
            data = {"pid": process.pid,
                    "status": process.status(),
                    "percent_cpu_used": process.cpu_percent(interval=0.0),
                    "percent_memory_used": process.memory_percent()}

        except (psutil.ZombieProcess, psutil.AccessDenied, psutil.NoSuchProcess):
            data = None

        if data is not None:
            pid_valid[process.name()] = data
    return pid_valid
项目:dcmha    作者:wwwbjqcom    | 项目源码 | 文件源码
def ReStart(groupname):
    '''??mysqlrouter'''
    restart_stat = None
    pids = psutil.pids()
    for pid in pids:
        p = psutil.Process(pid)
        cmdline = p.cmdline()
        if groupname+'.conf' in cmdline:
            try:
                os.kill(pid, 9)
                os.popen('cd /etc/mysqlrouter;nohup mysqlrouter -c mysqlrouter.conf -a %s.conf &' % groupname)
                return True
            except Exception,e:
                logging.error(traceback.format_exc())
                return False
            restart_stat = True
            break
    if restart_stat is None:
        os.popen('cd /etc/mysqlrouter;nohup mysqlrouter -c mysqlrouter.conf -a %s.conf &' % groupname)
项目:AutoML-Challenge    作者:postech-mlg-exbrain    | 项目源码 | 文件源码
def handle_tasks(tasks, time_limit, memory_limit, n_jobs=1, logger=None):
    window = []
    while len(tasks) > 0:
        while len(window) < n_jobs:
            if len(tasks) == 0:
                break
            job, sema = tasks.pop()
            window.append((job, time.time(), sema))
            job.start()
            if logger:
                logger.debug("Process %s start: %s MB is used" % (job.pid, memory_usage()))

        while len(window) == n_jobs:
            window = _check_window(window, time_limit, memory_limit, logger)

    while len(window) > 0:
        window = _check_window(window, time_limit, memory_limit, logger)
项目:ransomcare    作者:Happyholic1203    | 项目源码 | 文件源码
def on_crypto_ransom(self, evt):
        logger.debug('Whitelist: %s' % json.dumps(self.whitelist, indent=4))
        logger.debug('Suspended: %s' % json.dumps([
            {'pid': p.pid, 'exe': p.exe()} for p in self.suspended
        ], indent=4))
        if any(suspended.pid == evt.pid for suspended in self.suspended):
            return  # ignore captured ransom events

        try:
            p = psutil.Process(evt.pid)
            cmdline = p.cmdline()
        except (psutil.NoSuchProcess, psutil.AccessDenied):
            logger.warn('Suspicious process %d exited before being caught'
                        % evt.pid)
            return

        if cmdline not in self.whitelist:
            p.suspend()
            self.suspended.append(p)
            event.EventAskUserAllowOrDeny(p, evt.path).fire()
        else:
            logger.info('Allowed white-listed process: %d' % evt.pid)
项目:ransomcare    作者:Happyholic1203    | 项目源码 | 文件源码
def get_absolute_path(event_raw):
    '''
    Keeps a cache of processes' cwds, in case that their events might come
    after they're terminated.
    '''
    pid = event_raw.get('pid')
    path = event_raw.get('path')
    if path and path[0] == '/':
        return os.path.realpath(path)

    cwd = None
    logger.debug('%r' % pid_cwd)
    try:
        process = psutil.Process(pid)
        cwd = process.cwd()
        pid_cwd[pid] = cwd  # cache every pid's cwd
    except (psutil.NoSuchProcess, psutil.AccessDenied):
        cwd = pid_cwd.get(pid)
        if not cwd:
            return None

    return os.path.realpath(os.path.join(cwd, path))
项目:distiller    作者:pyoor    | 项目源码 | 文件源码
def check(proc, target_name, max_timeout):
    """
    Check CPU usage of target process
    """
    try:
        pid = proc.pid
        start_time = time()
        if psutil.Process(pid).children():
            for child in psutil.Process(pid).children():
                if child.name() == target_name:
                    while True:
                        cpu = all(0 == child.cpu_percent(interval=0.1) for x in xrange(8))
                        if cpu is not None and cpu is True:
                            kill(proc, child.pid)
                            break
                        if max_timeout is not None or max_timeout != 0:
                            end_time = time()
                            elapsed = end_time - start_time
                            if elapsed > max_timeout:
                                kill(proc, child.pid)
                                break
    except psutil.NoSuchProcess:
        pass
项目:isp-data-pollution    作者:essandess    | 项目源码 | 文件源码
def phantomjs_pid_and_memory(self):
        """ Return the pid and memory (MB) of the phantomjs process,
        restart if it's a zombie, and exit if a restart isn't working
        after three attempts. """
        for k in range(3):    # three strikes
            try:
                @self.phantomjs_short_timeout
                def phantomjs_process_pid(): return self.driver.service.process.pid
                pid = phantomjs_process_pid()
                rss_mb = psutil.Process(pid).memory_info().rss / float(2 ** 20)
                break
            except (psutil.NoSuchProcess,Exception) as e:
                if self.debug: print('.service.process.pid exception:\n{}'.format(e))
                self.quit_driver(pid=pid)
                self.open_driver()
        else:  # throw in the towel and exit if no viable phantomjs process after multiple attempts
            print('No viable phantomjs process after multiple attempts!')
            sys.exit(1)
        return (pid, rss_mb)
项目:tasker    作者:wavenator    | 项目源码 | 文件源码
def killing_loop(
        self,
    ):
        while self.stop_event.wait():
            if not psutil.pid_exists(self.pid_to_kill):
                return

            process = psutil.Process(self.pid_to_kill)
            if self.memory_limit != 0 and process.memory_info().rss >= self.memory_limit:
                os.kill(self.pid_to_kill, self.memory_limit_signal)

            if self.soft_timeout != 0 and self.time_elapsed >= self.soft_timeout:
                os.kill(self.pid_to_kill, self.soft_timeout_signal)

            if self.hard_timeout != 0 and self.time_elapsed >= self.hard_timeout:
                os.kill(self.pid_to_kill, self.hard_timeout_signal)

            if self.critical_timeout != 0 and self.time_elapsed >= self.critical_timeout:
                os.kill(self.pid_to_kill, self.critical_timeout_signal)

            time.sleep(self.sleep_interval)
            self.time_elapsed += self.sleep_interval
项目:tasker    作者:wavenator    | 项目源码 | 文件源码
def killing_loop(
        self,
    ):
        while self.stop_event.wait():
            if not psutil.pid_exists(self.pid_to_kill):
                return

            process = psutil.Process(self.pid_to_kill)
            if self.memory_limit != 0 and process.memory_info().rss >= self.memory_limit:
                os.kill(self.pid_to_kill, self.memory_limit_signal)

            with self.time_elapsed.get_lock():
                if self.soft_timeout != 0 and self.time_elapsed.value >= self.soft_timeout:
                    os.kill(self.pid_to_kill, self.soft_timeout_signal)

                if self.hard_timeout != 0 and self.time_elapsed.value >= self.hard_timeout:
                    os.kill(self.pid_to_kill, self.hard_timeout_signal)

                if self.critical_timeout != 0 and self.time_elapsed.value >= self.critical_timeout:
                    os.kill(self.pid_to_kill, self.critical_timeout_signal)

                self.time_elapsed.value += self.sleep_interval

            time.sleep(self.sleep_interval)
项目:incubator-airflow-old    作者:apache    | 项目源码 | 文件源码
def kill_using_shell(logger, pid, signal=signal.SIGTERM):
    try:
        process = psutil.Process(pid)
        # Use sudo only when necessary - consider SubDagOperator and SequentialExecutor case.
        if process.username() != getpass.getuser():
            args = ["sudo", "kill", "-{}".format(int(signal)), str(pid)]
        else:
            args = ["kill", "-{}".format(int(signal)), str(pid)]
        # PID may not exist and return a non-zero error code
        logger.error(subprocess.check_output(args, close_fds=True))
        logger.info("Killed process {} with signal {}".format(pid, signal))
        return True
    except psutil.NoSuchProcess as e:
        logger.warning("Process {} no longer exists".format(pid))
        return False
    except subprocess.CalledProcessError as e:
        logger.warning("Failed to kill process {} with signal {}. Output: {}"
                       .format(pid, signal, e.output))
        return False
项目:ecel    作者:ARL-UTEP-OC    | 项目源码 | 文件源码
def terminate(self):
        if not self.is_running():
            print ("  ...%s processes already dead" % self.name)
            return

        tps = []
        for process in self.processes:
            if process:
                parent_pid = process.pid
                parent = psutil.Process(parent_pid)
                try:
                    for child in parent.children(recursive=True):
                        child.kill()
                    parent.kill()
                except Exception as e:
                    print (" !! %s: %s" % (self.name, e))
                else:
                    tps.append(process.pid)
        print (" [x] Terminated: %s - pId(s): %s" % (self.name, ', '.join(str(p) for p in tps)))

        self.commands = []
        self.output_filenames = []
        self.processes = []
        self.pid_commands.clear()
项目:ecel    作者:ARL-UTEP-OC    | 项目源码 | 文件源码
def terminate(self):
        if not self.is_running():
            print ("  ...%s processes already dead" % self.name)
            return

        tps = []
        for process in self.processes:
            if process:
                parent_pid = process.pid
                parent = psutil.Process(parent_pid)
                try:
                    for child in parent.children(recursive=True):
                        child.kill()
                    parent.kill()
                except Exception as e:
                    print (" !! %s: %s" % (self.name, e))
                else:
                    tps.append(process.pid)
        print (" [x] Terminated: %s - pId(s): %s" % (self.name, ', '.join(str(p) for p in tps)))

        self.commands = []
        self.output_filenames = []
        self.processes = []
        self.pid_commands.clear()
项目:hydra    作者:lake-lerna    | 项目源码 | 文件源码
def terminate_process_and_children(self, name):
        """
        Recursively terminate all children of
        respective process
        @args:
        name:   Name of the job
        """
        if name not in self.jobs:
            print("[%s] does not exist as a process!", name)
        ppid = self.jobs[name]['process'].pid
        try:
            parent_proc = psutil.Process(ppid)
        except psutil.NoSuchProcess:
            return
        children = parent_proc.children(recursive=True)
        for proc in children:
            l.debug(proc)
            try:
                proc.send_signal(signal.SIGKILL)
            except:
                pass
项目:respeaker_virtualenv    作者:respeaker    | 项目源码 | 文件源码
def test_prlimit_availability(self):
        # prlimit() should be available starting from kernel 2.6.36
        p = psutil.Process(os.getpid())
        p.rlimit(psutil.RLIMIT_NOFILE)
        # if prlimit() is supported *at least* these constants should
        # be available
        self.assertTrue(hasattr(psutil, "RLIM_INFINITY"))
        self.assertTrue(hasattr(psutil, "RLIMIT_AS"))
        self.assertTrue(hasattr(psutil, "RLIMIT_CORE"))
        self.assertTrue(hasattr(psutil, "RLIMIT_CPU"))
        self.assertTrue(hasattr(psutil, "RLIMIT_DATA"))
        self.assertTrue(hasattr(psutil, "RLIMIT_FSIZE"))
        self.assertTrue(hasattr(psutil, "RLIMIT_LOCKS"))
        self.assertTrue(hasattr(psutil, "RLIMIT_MEMLOCK"))
        self.assertTrue(hasattr(psutil, "RLIMIT_NOFILE"))
        self.assertTrue(hasattr(psutil, "RLIMIT_NPROC"))
        self.assertTrue(hasattr(psutil, "RLIMIT_RSS"))
        self.assertTrue(hasattr(psutil, "RLIMIT_STACK"))
项目:respeaker_virtualenv    作者:respeaker    | 项目源码 | 文件源码
def test_open_files_file_gone(self):
        # simulates a file which gets deleted during open_files()
        # execution
        p = psutil.Process()
        files = p.open_files()
        with tempfile.NamedTemporaryFile():
            # give the kernel some time to see the new file
            call_until(p.open_files, "len(ret) != %i" % len(files))
            with mock.patch('psutil._pslinux.os.readlink',
                            side_effect=OSError(errno.ENOENT, "")) as m:
                files = p.open_files()
                assert not files
                assert m.called
            # also simulate the case where os.readlink() returns EINVAL
            # in which case psutil is supposed to 'continue'
            with mock.patch('psutil._pslinux.os.readlink',
                            side_effect=OSError(errno.EINVAL, "")) as m:
                self.assertEqual(p.open_files(), [])
                assert m.called

    # --- mocked tests
项目:respeaker_virtualenv    作者:respeaker    | 项目源码 | 文件源码
def test_exe_mocked(self):
        with mock.patch('psutil._pslinux.os.readlink',
                        side_effect=OSError(errno.ENOENT, "")) as m:
            # No such file error; might be raised also if /proc/pid/exe
            # path actually exists for system processes with low pids
            # (about 0-20). In this case psutil is supposed to return
            # an empty string.
            ret = psutil.Process().exe()
            assert m.called
            self.assertEqual(ret, "")

            # ...but if /proc/pid no longer exist we're supposed to treat
            # it as an alias for zombie process
            with mock.patch('psutil._pslinux.os.path.lexists',
                            return_value=False):
                self.assertRaises(psutil.ZombieProcess, psutil.Process().exe)
项目:respeaker_virtualenv    作者:respeaker    | 项目源码 | 文件源码
def test_process_create_time(self):
        cmdline = "ps -o lstart -p %s" % self.pid
        p = subprocess.Popen(cmdline, shell=1, stdout=subprocess.PIPE)
        output = p.communicate()[0]
        if PY3:
            output = str(output, sys.stdout.encoding)
        start_ps = output.replace('STARTED', '').strip()
        hhmmss = start_ps.split(' ')[-2]
        year = start_ps.split(' ')[-1]
        start_psutil = psutil.Process(self.pid).create_time()
        self.assertEqual(
            hhmmss,
            time.strftime("%H:%M:%S", time.localtime(start_psutil)))
        self.assertEqual(
            year,
            time.strftime("%Y", time.localtime(start_psutil)))
项目:respeaker_virtualenv    作者:respeaker    | 项目源码 | 文件源码
def test_serialization(self):
        def check(ret):
            if json is not None:
                json.loads(json.dumps(ret))
            a = pickle.dumps(ret)
            b = pickle.loads(a)
            self.assertEqual(ret, b)

        check(psutil.Process().as_dict())
        check(psutil.virtual_memory())
        check(psutil.swap_memory())
        check(psutil.cpu_times())
        check(psutil.cpu_times_percent(interval=0))
        check(psutil.net_io_counters())
        if LINUX and not os.path.exists('/proc/diskstats'):
            pass
        else:
            if not APPVEYOR:
                check(psutil.disk_io_counters())
        check(psutil.disk_partitions())
        check(psutil.disk_usage(os.getcwd()))
        check(psutil.users())
项目:respeaker_virtualenv    作者:respeaker    | 项目源码 | 文件源码
def test_ad_on_process_creation(self):
        # We are supposed to be able to instantiate Process also in case
        # of zombie processes or access denied.
        with mock.patch.object(psutil.Process, 'create_time',
                               side_effect=psutil.AccessDenied) as meth:
            psutil.Process()
            assert meth.called
        with mock.patch.object(psutil.Process, 'create_time',
                               side_effect=psutil.ZombieProcess(1)) as meth:
            psutil.Process()
            assert meth.called
        with mock.patch.object(psutil.Process, 'create_time',
                               side_effect=ValueError) as meth:
            with self.assertRaises(ValueError):
                psutil.Process()
            assert meth.called
项目:respeaker_virtualenv    作者:respeaker    | 项目源码 | 文件源码
def test_special_pid(self):
        p = psutil.Process(4)
        self.assertEqual(p.name(), 'System')
        # use __str__ to access all common Process properties to check
        # that nothing strange happens
        str(p)
        p.username()
        self.assertTrue(p.create_time() >= 0.0)
        try:
            rss, vms = p.memory_info()[:2]
        except psutil.AccessDenied:
            # expected on Windows Vista and Windows 7
            if not platform.uname()[1] in ('vista', 'win-7', 'win7'):
                raise
        else:
            self.assertTrue(rss > 0)
项目:pyupdater-wx-demo    作者:wettenhj    | 项目源码 | 文件源码
def PidIsRunning(pid):
    """
    Check if a process with PID pid is running.
    """
    try:
        proc = psutil.Process(int(pid))
        if proc.status == psutil.STATUS_DEAD:
            return False
        if proc.status == psutil.STATUS_ZOMBIE:
            return False
        return True  # Assume other status are valid
    except psutil.NoSuchProcess:
        return False
项目:spyking-circus    作者:spyking-circus    | 项目源码 | 文件源码
def process_errored(self):
        try:
            exit_code = self.process.exitCode()
        except Exception:
            exit_code = 0
        format = self.ui.edit_stdout.currentCharFormat()
        format.setFontWeight(QFont.Bold)
        format.setForeground(Qt.red)
        self.ui.edit_stdout.setCurrentCharFormat(format)
        self.ui.edit_stdout.appendPlainText('Process exited with exit code' % exit_code)
        self.restore_gui()
        self.ui.edit_stdout.setTextInteractionFlags(Qt.TextSelectableByMouse |
                                                    Qt.TextSelectableByKeyboard)
        self.process = None
项目:algo-trading-pipeline    作者:NeuralKnot    | 项目源码 | 文件源码
def check_processes(self):
        try:
            self.logger.log("Main", "informative", "Checking processes...")
            for process in self.processes:
                proc = psutil.Process(process.pid)
                if not proc.is_running():
                    self.logger.log("Main", "error", "Process crashed!  Exiting program.")
                    self.stop() # We can't trust the program after a process crashes.
            self.logger.log("Main", "informative", "Processes OK!")
        except Exception as e:
            self.logger.log("Main", "error", "Error checking processes: " + str(e))
            self.stop() # Stop here sinc a process probably died, causing this error

        self.gui.after(100, self.check_processes) # Check again in 100ms

    # Starts the processes
项目:genomedisco    作者:kundajelab    | 项目源码 | 文件源码
def get_rss_prop():  # this is quite expensive
    process = psutil.Process(os.getpid())
    return (process.memory_info().rss - process.memory_info().shared) / 10**6
项目:jx-sqlite    作者:mozilla    | 项目源码 | 文件源码
def __init__(self, description, debug=False, **parameters):
        self.debug = debug
        if debug:
            try:
                import os
                import psutil
                import gc

                self.description = description
                self.params = parameters
                self.start_memory = None
                self.process = psutil.Process(os.getpid())
            except Exception as e:
                Log.warning("problem in memory measure", cause=e)
项目:pybot    作者:spillai    | 项目源码 | 文件源码
def memory_usage_psutil():
    # return the memory usage in MB
    import psutil
    process = psutil.Process(os.getpid())
    mem = process.get_memory_info()[0] / float(2 ** 20)
    return mem
项目:pybot    作者:spillai    | 项目源码 | 文件源码
def getProcess():
    psutil = getPSUtil()
    if psutil:
        import os
        return psutil.Process( os.getpid() )
    return None
项目:pybot    作者:spillai    | 项目源码 | 文件源码
def printMemUsage():
    psutil = getPSUtil()
    if psutil:
        u = mem_usage()
        M = psutil.virtual_memory()
        print( "Process Mem: %0.1fMb     System: %0.1fMb / %0.1fMb"%(u, M.used/1048576., M.total/1048576.) )
项目:AntiRansom    作者:YJesus    | 项目源码 | 文件源码
def ownhandle() :
    my_regex = r".*" + re.escape(sys.argv[1]) + r".*"

    regex = re.compile(my_regex, re.IGNORECASE)

    for proc in psutil.process_iter():
        try:
            pinfo = proc.as_dict(attrs=['pid'])
        except psutil.NoSuchProcess:
            pass
        else:
            #print pinfo['pid']
            try:
                proci = psutil.Process(pinfo['pid'])
                for files in proci.open_files() :
                    #print files
                    #handles = re.match(my_regex, files, re.IGNORECASE)
                    match = regex.search(str(files))

                    #print match

                    if match is not None and pinfo['pid'] not in safepids :

                        return(pinfo['pid'])
            except :
                pass
项目:clicrud    作者:DavidJohnGee    | 项目源码 | 文件源码
def stop(self):
        StopCheck = True
        NumProcs = len(self._thread_list)
        ProcsStopped = 0
        while StopCheck:
            for _idx, _t in enumerate(self._thread_list):
                _qmsg = _t.finq
                if _qmsg == 'completed_run':
                    _t.stop()
                    ProcsStopped += 1
                    logging.info("Stopped thread %s with pid %s with kwargs \
                                 %s" % (_idx+1, _t.getPID(), _t))
                if _qmsg == 'error':
                    _t.stop()
                    logging.info("Error on thread %s with pid %s with kwargs \
                                 %s" % (_idx+1, _t.getPID(), _t))
                    StopCheck = False

                if NumProcs == ProcsStopped:
                    StopCheck = False
            sleep(0.5)

        print "\n\nGoodbye..."
        for pid in self._pid_list:
            p = psutil.Process(pid)
            p.terminate()
        exit(0)
项目:Harmonbot    作者:Harmon758    | 项目源码 | 文件源码
def benchmark(self):
        '''Benchmark'''
        process = psutil.Process()
        memory = process.memory_info().rss / 2 ** 20
        process.cpu_percent()
        embed = discord.Embed(color = clients.bot_color)
        embed.add_field(name = "RAM", value = "{:.2f} MiB".format(memory))
        embed.add_field(name = "CPU", value = "Calculating CPU usage..")
        message, embed = await self.bot.say(embed = embed)
        await asyncio.sleep(1)
        cpu = process.cpu_percent() / psutil.cpu_count()
        embed.set_field_at(1, name = "CPU", value = "{}%".format(cpu))
        await self.bot.edit_message(message, embed = embed)
项目:otest    作者:rohe    | 项目源码 | 文件源码
def kill_process(pid):
    proc = psutil.Process(pid)
    proc.kill()
项目:otest    作者:rohe    | 项目源码 | 文件源码
def pid_isrunning(pid):
    proc = psutil.Process(pid)
    return proc
项目:target-stitch    作者:singer-io    | 项目源码 | 文件源码
def __init__(self):
        self.process = psutil.Process()
        super().__init__(name='memory_reporter', daemon=True)
项目:ave    作者:sonyxperiadev    | 项目源码 | 文件源码
def close_fds(self, exclude):
        exclude.append(self.pipe.w)
        Process.close_fds(self, exclude)
项目:ave    作者:sonyxperiadev    | 项目源码 | 文件源码
def t5(pretty, factory):
    pipe = Pipe()
    p = P2(pipe)
    p.start()
    factory.processes.append(p)

    gc_pid = pipe.get()

    try:
        proc = psutil.Process(gc_pid)
    except Exception, e:
        print('FAIL %s: could not query grandchild: %s' % (pretty, e))
        return False

    os.kill(p.pid, signal.SIGKILL)

    ok = False
    for i in range(3):
        try:
            proc = psutil.Process(gc_pid)
        except psutil.NoSuchProcess:
            ok = True
            break
        time.sleep(0.5)

    if not ok:
        print('FAIL %s: could query grandchild: %s' % (pretty, proc))
        return False

    return True

# grandchild does not die when child dies if PDEATHSIG is unset?