How to use the psutil.Process function in psutil

To help you get started, we’ve selected a few psutil examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github elventear / psutil / test / test_psutil.py View on Github external
def test_get_open_files2(self):
        # test fd and path fields
        fileobj = open(TESTFN, 'r')
        p = psutil.Process(os.getpid())
        for path, fd in p.get_open_files():
            if path == fileobj.name or fd == fileobj.fileno():
                break
        else:
            self.fail("no file found; files=%s" % repr(p.get_open_files()))
        self.assertEqual(path, fileobj.name)
        if WINDOWS:
            self.assertEqual(fd, -1)
        else:
            self.assertEqual(fd, fileobj.fileno())
        # test positions
        ntuple = p.get_open_files()[0]
        self.assertEqual(ntuple[0], ntuple.path)
        self.assertEqual(ntuple[1], ntuple.fd)
        # test file is gone
        fileobj.close()
github ishepard / pydriller / tests / test_memory_consumption.py View on Github external
def test_memory():
    if 'TRAVIS' not in os.environ:
        return

    p = psutil.Process()
    mv = MemoryVisitor(p)

    start = datetime.now()
    RepositoryMining('test-repos/rails', mv,
                     from_commit='977b4be208c2c54eeaaf7b46953174ef402f49d4',
                     to_commit='ede505592cfab0212e53ca8ad1c38026a7b5d042').mine()
    end = datetime.now()

    diff = end - start
    print('Max memory {} Mb'.format(mv.maxMemory / (2 ** 20)))
    print('Min memory {} Mb'.format(mv.minMemory / (2 ** 20)))
    print('Min memory {} Mb'.format(', '.join(map(str, mv.all))))
    print('Time {}:{}:{}'.format(diff.seconds//3600, (diff.seconds//60)%60, diff.seconds))
github hxuhack / logic_bombs / run_tests.py View on Github external
def kill_all(process):
    parent = psutil.Process(process.pid)
    for child in parent.children(recursive=True):
        child.kill()
    parent.kill()
github radical-cybertools / radical.entk / design_helpers / procs_throughput / runme_procs.py View on Github external
pop_times = []
        q_len = []
        q_sizes = []
        proc_mem = []

        while (tasks_popped < 1000000)and(not kill_popper.is_set()):
            try:
                t = q.get()            

                tasks_popped +=1
                cur_time = time.time()

                pop_times.append(cur_time)
                q_len.append(q.qsize())                
                q_sizes.append(asizeof.asizeof(q))
                mem = psutil.Process(os.getpid()).memory_info().rss / float(2 ** 20) # MB
                proc_mem.append(mem)

                #    print '%s: Pop average throughput: %s tasks/sec'%(name, 
                #        float(tasks_popped/(cur_time - start_time)))
            
            except Empty:
                pass

        f = open(DATA + '/%s.txt'%name,'w')

        for ind in range(len(pop_times)):
            f.write('%s %s %s\n'%(pop_times[ind],q_len[ind],q_sizes[ind], proc_mem[ind]))
        f.close()

        print 'Pop proc killed'
github GambitResearch / suponoff / suponoff-monhelper.py View on Github external
def tailApplicationLog(self, pid, offset, length):
        try:
            cmdline = psutil.Process(pid).cmdline()
            logfile = get_application_logfile(cmdline)

            if logfile is None:
                return ['', 0, False]

            if not os.path.exists(logfile):
                # logbook rotated logfiles have a date even for today
                base, ext = os.path.splitext(logfile)
                logfile2 = "{}-{}{}".format(base,
                                            date.today().strftime("%Y-%m-%d"),
                                            ext)
                if os.path.exists(logfile2):
                    logfile = logfile2

            if not os.path.exists(logfile):
                # rotatelogs rotated logfiles...
github certbot / certbot / certbot / plugins / util.py View on Github external
return False

    listeners = [conn.pid for conn in net_connections
                 if conn.status == 'LISTEN' and
                 conn.type == socket.SOCK_STREAM and
                 conn.laddr[1] == port]
    try:
        if listeners and listeners[0] is not None:
            # conn.pid may be None if the current process doesn't have
            # permission to identify the listening process!  Additionally,
            # listeners may have more than one element if separate
            # sockets have bound the same port on separate interfaces.
            # We currently only have UI to notify the user about one
            # of them at a time.
            pid = listeners[0]
            name = psutil.Process(pid).name()
            display = zope.component.getUtility(interfaces.IDisplay)
            extra = ""
            if renewer:
                extra = RENEWER_EXTRA_MSG
            display.notification(
                "The program {0} (process ID {1}) is already listening "
                "on TCP port {2}. This will prevent us from binding to "
                "that port. Please stop the {0} program temporarily "
                "and then try again.{3}".format(name, pid, port, extra))
            return True
    except (psutil.NoSuchProcess, psutil.AccessDenied):
        # Perhaps the result of a race where the process could have
        # exited or relinquished the port (NoSuchProcess), or the result
        # of an OS policy where we're not allowed to look up the process
        # name (AccessDenied).
        pass
github midoks / mdserver-web / class / core / system_api.py View on Github external
def getPid(self, pname):
        try:
            if not self.pids:
                self.pids = psutil.pids()
            for pid in self.pids:
                if psutil.Process(pid).name() == pname:
                    return True
            return False
        except:
            return False
github AlexsLemonade / refinebio / workers / data_refinery_workers / processors / create_quantpendia.py View on Github external
def get_process_stats():
    BYTES_IN_GB = 1024 * 1024 * 1024
    process = psutil.Process(os.getpid())
    ram_in_GB = process.memory_info().rss / BYTES_IN_GB
    return {"total_cpu": psutil.cpu_percent(), "process_ram": ram_in_GB}
github prophyle / prophyle / prophyle / prophylelib.py View on Github external
message("Shell command:", command_str)

    if output_fn is None:
        if output_fo is None:
            out_fo = sys.stdout
        else:
            out_fo = output_fo
    else:
        out_fo = open(output_fn, "w+")

    if out_fo == sys.stdout:
        p = subprocess.Popen("/bin/bash -e -o pipefail -c '{}'".format(command_str), shell=True)
    else:
        p = subprocess.Popen("/bin/bash -e -o pipefail -c '{}'".format(command_str), shell=True, stdout=out_fo)

    ps_p = psutil.Process(p.pid)

    max_rss = 0
    error_code = None
    while error_code is None:
        try:
            max_rss = max(max_rss, ps_p.memory_info().rss)
        except (psutil.NoSuchProcess, psutil.ZombieProcess, psutil.AccessDenied, OSError, IOError):
            pass
        #except psutil.NoSuchProcess as e:
        #    print("[prophylelib] Warning: psutil - NoSuchProcess (pid: {}, name: {}, msg: {})".format(e.pid, e.name, e.msg), file=sys.stderr)

        # wait 0.2 s
        time.sleep(0.2)
        error_code = p.poll()

    out_fo.flush()
github muflone / gespeaker / gespeaker / engines / engine_espeak.py View on Github external
def pause(self, status):
    """Pause a previous play or resume after pause"""
    super(self.__class__, self).pause(status)
    if self.__process_speaker:
      # Show pause message when debug is activated
      self.settings.debug_line('%s %s engine with pid %d' % (
        status and 'Pause' or 'Resume',
        self.name, self.__process_speaker.pid))
      psprocess = psutil.Process(self.__process_speaker.pid)
      if status:
        psprocess.suspend()
      else:
        psprocess.resume()
    return True