Example #1
0
def refresh_window(procs, disks_read, disks_write):
    """Print results on screen by using curses."""
    curses.endwin()
    templ = "%-5s %-7s %11s %11s  %s"
    win.erase()

    disks_tot = "Total DISK READ: %s | Total DISK WRITE: %s" \
                % (bytes2human(disks_read), bytes2human(disks_write))
    print_line(disks_tot)

    header = templ % ("PID", "USER", "DISK READ", "DISK WRITE", "COMMAND")
    print_line(header, highlight=True)

    for p in procs:
        line = templ % (
            p.pid,
            p._username[:7],
            bytes2human(p._read_per_sec),
            bytes2human(p._write_per_sec),
            p._cmdline)
        try:
            print_line(line)
        except curses.error:
            break
    win.refresh()
Example #2
0
def main():
    stats = psutil.net_if_stats()
    io_counters = psutil.net_io_counters(pernic=True)
    for nic, addrs in psutil.net_if_addrs().items():
        print("%s:" % (nic))
        if nic in stats:
            st = stats[nic]
            print("    stats          : ", end='')
            print("speed=%sMB, duplex=%s, mtu=%s, up=%s" % (
                st.speed, duplex_map[st.duplex], st.mtu,
                "yes" if st.isup else "no"))
        if nic in io_counters:
            io = io_counters[nic]
            print("    incoming       : ", end='')
            print("bytes=%s, pkts=%s, errs=%s, drops=%s" % (
                bytes2human(io.bytes_recv), io.packets_recv, io.errin,
                io.dropin))
            print("    outgoing       : ", end='')
            print("bytes=%s, pkts=%s, errs=%s, drops=%s" % (
                bytes2human(io.bytes_sent), io.packets_sent, io.errout,
                io.dropout))
        for addr in addrs:
            print("    %-4s" % af_map.get(addr.family, addr.family), end="")
            print(" address   : %s" % addr.address)
            if addr.broadcast:
                print("         broadcast : %s" % addr.broadcast)
            if addr.netmask:
                print("         netmask   : %s" % addr.netmask)
            if addr.ptp:
                print("      p2p       : %s" % addr.ptp)
        print("")
Example #3
0
def print_process(metric):
    """ functions sort, filter and print process are based on
        metric argument provided by the user to the script.
        mem - filtered by value from mem_val variable in Mb
        cpu - filtered by value from proc_num variable qty
    """

    print('{:>8}{:>20}{:>20}{:>20}{:>20}'.format('pid', 'name', 'CPU Time',
                                                 'Memory', 'User'))

    if metric == 'mem':
        mem = psutil.process_iter(
            ['name', 'cpu_times', 'memory_info', 'username'])
        mem_sorted = sorted(mem,
                            reverse=True,
                            key=lambda p: p.info['memory_info'])
        for p in mem_sorted:
            if p.info['memory_info'].rss > mem_val * 1024 * 1024:
                print('{:>8}{:>20}{:>20.2f}{:>20}{:>20}'.format(
                    p.pid, p.info['name'], sum(p.info['cpu_times']),
                    bytes2human(p.info['memory_info'].rss),
                    str(p.info['username'])))
    else:
        proc = psutil.process_iter(
            ['name', 'cpu_times', 'memory_info', 'username'])
        proc_sorted = sorted(proc,
                             reverse=True,
                             key=lambda p: sum(p.info['cpu_times'][:2]))
        for p in proc_sorted[:proc_num]:
            print('{:>8}{:>20}{:>20.2f}{:>20}{:>20}'.format(
                p.pid, p.info['name'], sum(p.info['cpu_times']),
                bytes2human(p.info['memory_info'].rss),
                str(p.info['username'])))
Example #4
0
 def virt_memory(self):
     print("Virtual Memory Stats: ")
     template = "{0:^16} {1:^16} {2:^16} {3:^16} {4:^16}"
     virtual = psutil.virtual_memory()
     print(template.format("Total ","Available memory","Used memory","Free memory","Percent"))
     print(template.format(bytes2human(virtual.total),bytes2human(virtual.available),bytes2human(virtual.used),bytes2human(virtual.free),str(virtual.percent)+ "%"))
     print("\n")
def data_treatment_memory(time):
    """
    Treats the memory usage data and writes it to textfile and mariadb
    """
    memory_usage = get_memory_usage()
    memory_total = memory_usage.total
    readable_total = bytes2human(memory_total)
    memory_used = memory_usage.used
    readable_used = bytes2human(memory_used)
    memory_percent = calculate_memory_usage()
    sqlstatement = f"INSERT INTO " \
                   f"memory_usage" \
                   f"(" \
                   f"total_memory, " \
                   f"used_memory, " \
                   f"memory_total_read, " \
                   f"memory_used_read, " \
                   f"percent_used " \
                   f") " \
                   f"VALUES (" \
                   f"'{memory_total}'," \
                   f" '{memory_used}', " \
                   f" '{readable_total}', " \
                   f" '{readable_used}', " \
                   f"'{memory_percent}')"
    write_to_db(sqlstatement)
    file_line = f"{time} Memory usage :\t {memory_percent} % of {readable_total}"
    write_to_file(file_line)
Example #6
0
def print_io_stats(io):
    print("    incoming       : ", end='')
    print("bytes={}, pkts={}, errs={}, drops={}".format(
        bytes2human(io.bytes_recv), io.packets_recv, io.errin, io.dropin))
    print("    outgoing       : ", end='')
    print("bytes={}, pkts={}, errs={}, drops={}".format(
        bytes2human(io.bytes_sent), io.packets_sent, io.errout, io.dropout))
    def _pid_info(self, text=None):
        print('INICIO DO EVENTO:', time.ctime(), text)
        name = 'python.exe'
        lp = psutil.pids()
        info_dict = dict()
        for i in lp:
            try:
                p = psutil.Process(i)
                exec_path = p.exe()
                if psutil.pid_exists(i) and p.name() == name:
                    info_dict['Executável'] = exec_path.split('\\')[-1]
                    info_dict['PID'] = i
                    info_dict['Threads'] = p.num_threads()
                    info_dict['Criação'] = time.ctime(p.create_time())
                    info_dict['T. Usu.'] = p.cpu_times().user
                    info_dict['T. Sis.'] = p.cpu_times().system
                    info_dict['Mem. (%)'] = round(p.memory_percent(), 2)
                    info_dict['RSS'] = bytes2human(p.memory_info().rss)
                    info_dict['VMS'] = bytes2human(p.memory_info().vms)
            except:
                pass
        for pid, info_pid in info_dict.items():
            print('{}{:<10}: {:<30}'.format(' ' * 2, pid, info_pid))

        print('FIM DO EVENTO:', time.ctime(), text)
        return info_dict
Example #8
0
def get_stats(request):
    context = {}
    context["cpu_usage"] = json.dumps(psutil.cpu_percent(interval=None, percpu=False))

    total_memory = psutil.virtual_memory()

    dict(psutil.virtual_memory()._asdict())
    used_ram = psutil.virtual_memory().percent
    available_ram = psutil.virtual_memory().available * 100 / psutil.virtual_memory().total

    context["free_ram"] = json.dumps(available_ram)
    context["used_ram"] = json.dumps(used_ram)

    disk_usage = []
    for part in psutil.disk_partitions(all=False):
            if os.name == 'nt':
                if 'cdrom' in part.opts or part.fstype == '':
                    # skip cd-rom drives with no disk in it; they may raise
                    # ENOENT, pop-up a Windows GUI error for a non-ready
                    # partition or just hang.
                    continue
            usage = psutil.disk_usage(part.mountpoint)
            disk_usage.append(
                {
                    "device": part.device,
                    "total": bytes2human(usage.total),
                    "used": bytes2human(usage.used),
                    "free": bytes2human(usage.free),
                    "percent": int(usage.percent),
                    "fs_type": part.fstype,
                    "mountpoint": part.mountpoint
                })
    context["disk_usage"] = json.dumps(disk_usage)

    return JsonResponse(context)
def data_treatment_net_io(time):
    """
    Treats the net io data and writes it to textfile and mariadb
    """
    counters = get_net_io_counters()
    for nic_name in counters:
        bytes_sent = counters[nic_name].bytes_sent
        readable_sent = bytes2human(bytes_sent)
        bytes_received = counters[nic_name].bytes_recv
        readable_received = bytes2human(bytes_received)
        sqlstatement = f"INSERT INTO " \
                       f"net_io_counter" \
                       f"(" \
                       f"host," \
                       f"nic, " \
                       f"bytes_sent, " \
                       f"bytes_received, " \
                       f"readable_sent," \
                       f"readable_received" \
                       f") " \
                       f"VALUES (" \
                       f" '{host}'," \
                       f" '{nic_name}', " \
                       f" '{bytes_sent}', " \
                       f" '{bytes_received}', " \
                       f" '{readable_sent}', " \
                       f" '{readable_received}')"
        if len(nic_name) < 6:
            file_line = f"{time} NIC : {nic_name}\t \t reception : " \
                        f"{readable_received}\t sending : {readable_received}"
        else:
            file_line = f"{time} NIC : {nic_name}\t reception : " \
                        f"{readable_received}\t sending : {readable_received}"
        write_to_file(file_line)
        write_to_db(sqlstatement)
Example #10
0
def get_net_info():
    import socket
    net_info_dic = {}
    if_stats_dic = psutil.net_if_stats()
    if_addrs_dic = psutil.net_if_addrs()
    io_counters_obj = psutil.net_io_counters()

    for nic, addrs in if_addrs_dic.items():
        if not nic.startswitch('lo'):
            net_info_dic[nic] = {'nic_stat': if_stats_dic[nic].isup}
            for addr in addrs:
                if addr.family == socket.AF_INET:
                    net_info_dic[nic].update({
                        'ip': addr.address,
                        'netmask': addr.netmask
                    })

    for item in net_info_dic.values():
        item.setdefault('ip', '')
        item.setdefault('netmask', '')

    net_info_dic['io_info'] = {
        'bytes_sent': bytes2human(io_counters_obj.bytes_sent),
        'bytes_recv': bytes2human(io_counters_obj.bytes_recv),
        'packe_sent': io_counters_obj.packets_sent,
        'packe_recv': io_counters_obj.packets_recv,
    }

    return net_info_dic
Example #11
0
def main():
    stats = psutil.net_if_stats()
    io_counters = psutil.net_io_counters(pernic=True)
    for nic, addrs in psutil.net_if_addrs().items():  # key와 value 두개의 인자값을 반복문을 통해 꺼낸다.
        print("%s:" % (nic))                          # nic를 출력한다.
        if nic in stats:                              # stats 안에 nic가 있으면
            st = stats[nic]                           # stats[nic] key에 대응하는 Value를 변수 st에 넣는다.
            # st =  snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_UNKNOWN: 0>, speed=0, mtu=1380)
            print("    stats          : ", end='')    # end=''를 지정하여 줄바꿈하지 않는다.
            print("speed=%sMB, duplex=%s, mtu=%s, up=%s" % ( # 즐 바꿈하지 않은 상태에서 각 요소들을 문자열 변수에 담아 출력한다.
                st.speed, duplex_map[st.duplex], st.mtu,     # 위에서 설정한 duplex_map에서 st.duplex에 해당하는 값을 가져온다.
                "yes" if st.isup else "no"                   # isup가 TRUE면 "yes"를 출력하고 그렇지 않으면 "no"를 출력.
            ))
        if nic in io_counters:                          # io_conters에 nic가 있으면, nic에 해당하는 값을 io에 담는다.
            io = io_counters[nic]
            print("    incoming       : ", end='')      # 줄바꿈하지 않은 상태에서 문자열 변수를 담아 출력한다.
            print("bytes=%s, pkts=%s, errs=%s, drops=%s" % (
                bytes2human(io.bytes_recv), io.packets_recv, io.errin,
                io.dropin       # 예) io.bytes_recv => 120899579904
            ))
            print("    outgoing       : ", end='')
            print("bytes=%s, pkts=%s, errs=%s, drops=%s" % (
                bytes2human(io.bytes_sent), io.packets_sent, io.errout,
                io.dropout
            ))
        for addr in addrs:  # addrs 딕셔너리에서 모든 addr 요소를 반복문을 통해 꺼낸다. 예) snicaddr(family=<AddressFamily.AF_INET: 2>, address='127.0.0.1', netmask='255.0.0.0', broadcast=None, ptp=None)
            print("    %-4s" % af_map.get(addr.family, addr.family), end="") # af_map 딕셔너리에서 addr.family의 value를 꺼낸다.
            print(" address   : %s" % addr.address) # 모든 address를 하나씩 출력한다.
            if addr.broadcast:
                print("    broadcast      : %s" % addr.broadcast)   # address가 브로드캐스
            if addr.netmask:
                print("    netmask        : %s" % addr.netmask)    # address가 netmask
            if addr.ptp:
                print("    p2p          : %s" % addr.ptp)           # address가 ptp
        print("")   # 출력되는 nic 정보 아래에 빈 칸을 생성한다.
Example #12
0
def refresh_window(procs, disks_read, disks_write):
    """Print results on screen by using curses."""
    curses.endwin()
    templ = "%-5s %-7s %11s %11s  %s"
    win.erase()

    disks_tot = "Total DISK READ: %s | Total DISK WRITE: %s" \
                % (bytes2human(disks_read), bytes2human(disks_write))
    print_line(disks_tot)

    header = templ % ("PID", "USER", "DISK READ", "DISK WRITE", "COMMAND")
    print_line(header, highlight=True)

    for p in procs:
        line = templ % (
            p.pid,
            p._username[:7],
            bytes2human(p._read_per_sec),
            bytes2human(p._write_per_sec),
            p._cmdline)
        try:
            print_line(line)
        except curses.error:
            break
    win.refresh()
Example #13
0
    async def run(self) -> None:
        self.interface = self._find_interface(self.interface)

        if not self.interface:
            self.update(self.format_down, color=types.Color.URGENT)
            return

        now = psutil.net_io_counters(pernic=True)
        now_time = time.time()

        if self.interface in now.keys():
            upload, download = self._calculate_speed(
                self.previous[self.interface],
                self.previous_time,
                now[self.interface],
                now_time,
            )
        else:
            upload, download = 0, 0

        color = misc.calculate_threshold(self.colors, max(upload, download))

        self.update(
            self.ex_format(
                self.format_up,
                upload=bytes2human(upload),
                download=bytes2human(download),
                interface=self.interface,
            ),
            color=color,
        )

        self.previous = now
        self.previous_time = now_time
Example #14
0
def main():

    import time
    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    import psutil
    from psutil._common import bytes2human
    from pympler.asizeof import asizeof

    p = psutil.Process()

    x = np.linspace(1,10**4,10)
    for n in x:
        measure_this = pd.DataFrame(np.zeros(shape=(int(n),int(n))))
        print("Mem of df: ", bytes2human(asizeof(measure_this)))

        memory = p.memory_full_info()
        print("Mem of process before del: ", bytes2human(memory.rss))
        print("Mem of process before del: ", bytes2human(memory.vms))

        del measure_this
        memory = p.memory_full_info()
        print("Mem of process after del: ", bytes2human(memory.rss))
        print("Mem of process after del: ", bytes2human(memory.vms))

    return
Example #15
0
def main():
    groups = collections.defaultdict(list)
    for path in glob.glob('dist/*.whl'):
        wheel = Wheel(path)
        groups[wheel.platform()].append(wheel)

    tot_files = 0
    tot_size = 0
    templ = "%-54s %7s %7s %7s"
    for platf, wheels in groups.items():
        ppn = "%s (total = %s)" % (platf, len(wheels))
        s = templ % (ppn, "size", "arch", "pyver")
        print_color('\n' + s, color=None, bold=True)
        for wheel in sorted(wheels, key=lambda x: x.name):
            tot_files += 1
            tot_size += wheel.size()
            s = templ % (wheel.name, bytes2human(wheel.size()), wheel.arch(),
                         wheel.pyver())
            if 'pypy' in wheel.pyver():
                print_color(s, color='violet')
            else:
                print_color(s, color='brown')

    print_color("\ntotals: files=%s, size=%s" % (
        tot_files, bytes2human(tot_size)), bold=True)
    def _directory_file_info(self, text=None):
        print('INICIO DO EVENTO:', time.ctime(), text)
        path = ".\\"
        os.chdir(path)
        current_path = os.getcwd()
        dir_list = os.listdir(current_path)
        info_dict = dict()

        if text == 'arquivo':
            for i in dir_list:
                if os.path.isfile(i):
                    ext = os.path.splitext(i)[1]
                    if not ext in info_dict:
                        info_dict[ext] = dict()
                    info_dict[ext][i] = [
                        bytes2human(os.stat(i).st_size),
                        time.ctime(os.stat(i).st_mtime),
                        time.ctime(os.stat(i).st_atime)
                    ]
                else:
                    pass
        else:
            for i in dir_list:
                if not os.path.isfile(i):
                    if not i in info_dict:
                        info_dict[i] = list()
                    info_dict[i] = [
                        bytes2human(os.stat(i).st_size),
                        time.ctime(os.stat(i).st_atime),
                        time.ctime(os.stat(i).st_mtime)
                    ]
                else:
                    pass

        return info_dict
def memory_info():
    dic_memory = {}
    memoria = psutil.virtual_memory()
    dic_memory['porcentagem'] = "{}%".format(memoria.percent)
    dic_memory['total'] = bytes2human(memoria.total)
    dic_memory['usada'] = bytes2human(memoria.used)
    dic_memory['free'] = bytes2human(memoria.free)
    return dic_memory
Example #18
0
def main():
    today_day = datetime.date.today()
    templ = "%-10s %5s %5s %7s %7s %5s %6s %6s %6s  %s"
    attrs = ['pid', 'memory_percent', 'name', 'cmdline', 'cpu_times',
             'create_time', 'memory_info', 'status', 'nice', 'username']
    print(templ % ("USER", "PID", "%MEM", "VSZ", "RSS", "NICE",
                   "STATUS", "START", "TIME", "CMDLINE"))
    for p in psutil.process_iter(attrs, ad_value=None):
        if p.info['create_time']:
            ctime = datetime.datetime.fromtimestamp(p.info['create_time'])
            if ctime.date() == today_day:
                ctime = ctime.strftime("%H:%M")
            else:
                ctime = ctime.strftime("%b%d")
        else:
            ctime = ''
        if p.info['cpu_times']:
            cputime = time.strftime("%M:%S",
                                    time.localtime(sum(p.info['cpu_times'])))
        else:
            cputime = ''

        user = p.info['username']
        if not user and psutil.POSIX:
            try:
                user = p.uids()[0]
            except psutil.Error:
                pass
        if user and psutil.WINDOWS and '\\' in user:
            user = user.split('\\')[1]
        if not user:
            user = ''
        user = user[:9]
        vms = bytes2human(p.info['memory_info'].vms) if \
            p.info['memory_info'] is not None else ''
        rss = bytes2human(p.info['memory_info'].rss) if \
            p.info['memory_info'] is not None else ''
        memp = round(p.info['memory_percent'], 1) if \
            p.info['memory_percent'] is not None else ''
        nice = int(p.info['nice']) if p.info['nice'] else ''
        if p.info['cmdline']:
            cmdline = ' '.join(p.info['cmdline'])
        else:
            cmdline = p.info['name']
        status = p.info['status'][:5] if p.info['status'] else ''

        line = templ % (
            user,
            p.info['pid'],
            memp,
            vms,
            rss,
            nice,
            status,
            ctime,
            cputime,
            cmdline)
        print(line[:get_terminal_size()[0]])
Example #19
0
def main():
    today_day = datetime.date.today()
    templ = "%-10s %5s %5s %7s %7s %5s %6s %6s %6s  %s"
    attrs = ['pid', 'memory_percent', 'name', 'cmdline', 'cpu_times',
             'create_time', 'memory_info', 'status', 'nice', 'username']
    print(templ % ("USER", "PID", "%MEM", "VSZ", "RSS", "NICE",
                   "STATUS", "START", "TIME", "CMDLINE"))
    for p in psutil.process_iter(attrs, ad_value=None):
        if p.info['create_time']:
            ctime = datetime.datetime.fromtimestamp(p.info['create_time'])
            if ctime.date() == today_day:
                ctime = ctime.strftime("%H:%M")
            else:
                ctime = ctime.strftime("%b%d")
        else:
            ctime = ''
        if p.info['cpu_times']:
            cputime = time.strftime("%M:%S",
                                    time.localtime(sum(p.info['cpu_times'])))
        else:
            cputime = ''

        user = p.info['username']
        if not user and psutil.POSIX:
            try:
                user = p.uids()[0]
            except psutil.Error:
                pass
        if user and psutil.WINDOWS and '\\' in user:
            user = user.split('\\')[1]
        if not user:
            user = ''
        user = user[:9]
        vms = bytes2human(p.info['memory_info'].vms) if \
            p.info['memory_info'] is not None else ''
        rss = bytes2human(p.info['memory_info'].rss) if \
            p.info['memory_info'] is not None else ''
        memp = round(p.info['memory_percent'], 1) if \
            p.info['memory_percent'] is not None else ''
        nice = int(p.info['nice']) if p.info['nice'] else ''
        if p.info['cmdline']:
            cmdline = ' '.join(p.info['cmdline'])
        else:
            cmdline = p.info['name']
        status = p.info['status'][:5] if p.info['status'] else ''

        line = templ % (
            user,
            p.info['pid'],
            memp,
            vms,
            rss,
            nice,
            status,
            ctime,
            cputime,
            cmdline)
        print(line[:get_terminal_size()[0]])
Example #20
0
    def execute(self, fun, *args, **kwargs):
        """Test a callable."""
        def call_many_times():
            for x in xrange(loops):
                self._call(fun, *args, **kwargs)
            del x
            gc.collect()

        tolerance = kwargs.pop('tolerance_', None) or self.tolerance
        loops = kwargs.pop('loops_', None) or self.loops
        retry_for = kwargs.pop('retry_for_', None) or self.retry_for

        # warm up
        for x in range(10):
            self._call(fun, *args, **kwargs)
        self.assertEqual(gc.garbage, [])
        self.assertEqual(threading.active_count(), 1)
        self.assertEqual(thisproc.children(), [])

        # Get 2 distinct memory samples, before and after having
        # called fun repeadetly.
        # step 1
        call_many_times()
        mem1 = self._get_mem()
        # step 2
        call_many_times()
        mem2 = self._get_mem()

        diff1 = mem2 - mem1
        if diff1 > tolerance:
            # This doesn't necessarily mean we have a leak yet.
            # At this point we assume that after having called the
            # function so many times the memory usage is stabilized
            # and if there are no leaks it should not increase
            # anymore.
            # Let's keep calling fun for 3 more seconds and fail if
            # we notice any difference.
            ncalls = 0
            stop_at = time.time() + retry_for
            while time.time() <= stop_at:
                self._call(fun, *args, **kwargs)
                ncalls += 1

            del stop_at
            gc.collect()
            mem3 = self._get_mem()
            diff2 = mem3 - mem2

            if mem3 > mem2:
                # failure
                extra_proc_mem = bytes2human(diff1 + diff2)
                print("exta proc mem: %s" % extra_proc_mem, file=sys.stderr)
                msg = "+%s after %s calls, +%s after another %s calls, "
                msg += "+%s extra proc mem"
                msg = msg % (
                    bytes2human(diff1), loops, bytes2human(diff2), ncalls,
                    extra_proc_mem)
                self.fail(msg)
Example #21
0
def virtual_ram():
    result = {}
    mem = psutil.virtual_memory()
    result['total'] = bytes2human(mem.total)
    result['available'] = bytes2human(mem.available)
    result['percent'] = mem.percent
    result['used'] = bytes2human(mem.used)
    result['free'] = bytes2human(mem.free)
    return result
Example #22
0
def diskusage():
    usage = psutil.disk_usage('/')
    d = "Disk Usage:\n\n"
    t = ("Total: {}".format(bytes2human(usage.total)))
    u = ("\nUsed: {}".format(bytes2human(usage.used)))
    f = ("\nFree: {}".format(bytes2human(usage.free)))
    p = ("\nPercent: %s%%" % round(usage.percent, 2))
    results = (d + t + u + f + p)
    window.FindElement('wipe2').Update(results)
Example #23
0
def partition():
    print(color.BLUE + 'Disk Usage:' + color.END)
    templ = "%-17s %8s %8s %8s %5s%% %9s  %s"
    print(templ % ("Device", "Total", "Used", "Free", "Use ", "Type", "Mount"))
    for part in psutil.disk_partitions(all=False):
        usage = psutil.disk_usage(part.mountpoint)
        print(templ % (part.device, bytes2human(
            usage.total), bytes2human(usage.used), bytes2human(
                usage.free), int(usage.percent), part.fstype, part.mountpoint))
Example #24
0
def memory():
    usage = psutil.virtual_memory()
    m = "Memory Statistics:\n\n"
    t = ("Total: {}".format(bytes2human(usage.total)))
    u = ("\nUsed: {}".format(bytes2human(usage.used)))
    f = ("\nFree: {}".format(bytes2human(usage.free)))
    p = ("\nPercent: %s%%" % round(usage.percent, 2))
    results = (m + t + u + f + p)
    window.FindElement('wipe2').Update(results)
Example #25
0
 def diskusage():
     usage = psutil.disk_usage('/')
     d = "Disk Usage:\n\n"
     t = ("Total: {}".format(bytes2human(usage.total)))
     u = ("\nUsed: {}".format(bytes2human(usage.used)))
     f = ("\nFree: {}".format(bytes2human(usage.free)))
     p = ("\nPercent: %s%%" % round(usage.percent, 2))
     #p = ("\nPercent: {}".format(bytes2human(usage.percent)))
     results = (d + t + u + f + p)
     outputText.insert(END, results)
Example #26
0
def ram():
    mem = psutil.virtual_memory(
    )  #returns the current RAM usage as a named tupel
    total = str(bytes2human(mem.total))  #total physical memory
    available = str(
        bytes2human(mem.available)
    )  #the memory that can be given instantly to process without the system going into swap
    active = str(bytes2human(mem.active))  #memory currently in use
    inactive = str(bytes2human(mem.inactive))  #memory marked as not used
    return 'total memory: ' + total + '; ' + 'available memory: ' + available + '; ' + ' active memory: ' + active + '; ' + 'inactive memory: ' + inactive
Example #27
0
 def memory():
     usage = psutil.virtual_memory()
     m = "Memory Statistics:\n\n"
     t = ("Total: {}".format(bytes2human(usage.total)))
     u = ("\nUsed: {}".format(bytes2human(usage.used)))
     f = ("\nFree: {}".format(bytes2human(usage.free)))
     p = ("\nPercent: %s%%" % round(usage.percent, 2))
     #p = ("\nPercent: {}".format(bytes2human(usage.percent)))
     results = (m + t + u + f + p)
     outputText.insert(END, results)
Example #28
0
    def process_data(self):
        """ This function process the input data from init_class. """
        for field in psutil.virtual_memory()._fields:
            if field == 'total':
                self.virtual_memory['total'] = bytes2human(
                    getattr(psutil.virtual_memory(), field))

        for field in psutil.swap_memory()._fields:
            if field == 'total':
                self.swap_memory['total'] = bytes2human(
                    getattr(psutil.swap_memory(), field))
Example #29
0
def disk_usage():
    templ = "%-17s %8s %8s %8s %8s%% %9s  %s"
    print(templ % ("Device", "Total", "Used", "Free", "Use ", "Type", "Mount"))
    for part in psutil.disk_partitions(all=False):
        # if os.name == 'nt':
        #     if 'cdrom' in part.opts or part.fstype == '':
        #         continue
        usage = psutil.disk_usage(part.mountpoint)
        print(templ % (part.device, bytes2human(
            usage.total), bytes2human(usage.used), bytes2human(
                usage.free), int(usage.percent), part.fstype, part.mountpoint))
Example #30
0
def test_ram(app, client):
    mem = psutil.virtual_memory()
    total = str(bytes2human(mem.total))
    available = str(bytes2human(mem.available))
    active = str(bytes2human(mem.active))
    inactive = str(bytes2human(mem.inactive))

    res = client.get('/ram')
    assert res.status_code == 200
    expected = 'total memory: ' + total + '; ' + 'available memory: ' + available + '; ' + ' active memory: ' + active + '; ' + 'inactive memory: ' + inactive
    assert expected == res.get_data(as_text=True)
Example #31
0
def print_header(procs_status, num_procs):
    """Print system-related info, above the process list."""
    def get_dashes(perc):
        dashes = "|" * int((float(perc) / 10 * 4))
        empty_dashes = " " * (40 - len(dashes))
        return dashes, empty_dashes

    # cpu usage
    percs = psutil.cpu_percent(interval=0, percpu=True)
    for cpu_num, perc in enumerate(percs):
        dashes, empty_dashes = get_dashes(perc)
        line = " CPU%-2s [%s%s] %5s%%" % (cpu_num, dashes, empty_dashes, perc)
        printl(line, color=get_color(perc))

    # memory usage
    mem = psutil.virtual_memory()
    dashes, empty_dashes = get_dashes(mem.percent)
    line = " Mem   [%s%s] %5s%% %6s / %s" % (
        dashes,
        empty_dashes,
        mem.percent,
        bytes2human(mem.used),
        bytes2human(mem.total),
    )
    printl(line, color=get_color(mem.percent))

    # swap usage
    swap = psutil.swap_memory()
    dashes, empty_dashes = get_dashes(swap.percent)
    line = " Swap  [%s%s] %5s%% %6s / %s" % (
        dashes,
        empty_dashes,
        swap.percent,
        bytes2human(swap.used),
        bytes2human(swap.total),
    )
    printl(line, color=get_color(swap.percent))

    # processes number and status
    st = []
    for x, y in procs_status.items():
        if y:
            st.append("%s=%s" % (x, y))
    st.sort(key=lambda x: x[:3] in ('run', 'sle'), reverse=1)
    printl(" Processes: %s (%s)" % (num_procs, ', '.join(st)))
    # load average, uptime
    uptime = datetime.datetime.now() - \
        datetime.datetime.fromtimestamp(psutil.boot_time())
    av1, av2, av3 = psutil.getloadavg()
    line = " Load average: %.2f %.2f %.2f  Uptime: %s" \
        % (av1, av2, av3, str(uptime).split('.')[0])
    printl(line)
Example #32
0
def main():
    def is64bit(name):
        return name.endswith(('x86_64.whl', 'amd64.whl'))

    groups = collections.defaultdict(list)
    for path in glob.glob('dist/*.whl'):
        name = os.path.basename(path)
        plat = name.split('-')[-1]
        pyimpl = name.split('-')[3]
        ispypy = 'pypy' in pyimpl
        if 'linux' in plat:
            if ispypy:
                groups['pypy_on_linux'].append(name)
            else:
                groups['linux'].append(name)
        elif 'win' in plat:
            if ispypy:
                groups['pypy_on_windows'].append(name)
            else:
                groups['windows'].append(name)
        elif 'macosx' in plat:
            if ispypy:
                groups['pypy_on_macos'].append(name)
            else:
                groups['macos'].append(name)
        else:
            assert 0, name

    tot_files = 0
    tot_size = 0
    templ = "%-54s %7s %7s %7s"
    for platf, names in groups.items():
        ppn = "%s (total = %s)" % (platf.replace('_', ' '), len(names))
        s = templ % (ppn, "size", "arch", "pyver")
        print_color('\n' + s, color=None, bold=True)
        for name in sorted(names):
            tot_files += 1
            path = os.path.join('dist', name)
            size = os.path.getsize(path)
            tot_size += size
            arch = '64' if is64bit(name) else '32'
            pyver = 'pypy' if name.split('-')[3].startswith('pypy') else 'py'
            pyver += name.split('-')[2][2:]
            s = templ % (name, bytes2human(size), arch, pyver)
            if 'pypy' in pyver:
                print_color(s, color='violet')
            else:
                print_color(s, color='brown')

    print_color("\ntotals: files=%s, size=%s" %
                (tot_files, bytes2human(tot_size)),
                bold=1)
Example #33
0
def str_ntuple(nt, convert_bytes=False):
    if nt == ACCESS_DENIED:
        return ""
    if not convert_bytes:
        return ", ".join(["%s=%s" % (x, getattr(nt, x)) for x in nt._fields])
    else:
        return ", ".join(["%s=%s" % (x, bytes2human(getattr(nt, x)))
                          for x in nt._fields])
Example #34
0
def main():
    if len(sys.argv) != 2:
        sys.exit('usage: pmap <pid>')
    p = psutil.Process(int(sys.argv[1]))
    templ = "%-20s %10s  %-7s %s"
    print(templ % ("Address", "RSS", "Mode", "Mapping"))
    total_rss = 0
    for m in p.memory_maps(grouped=False):
        total_rss += m.rss
        safe_print(templ % (
            m.addr.split('-')[0].zfill(16),
            bytes2human(m.rss),
            m.perms,
            m.path))
    print("-" * 31)
    print(templ % ("Total", bytes2human(total_rss), '', ''))
    safe_print("PID = %s, name = %s" % (p.pid, p.name()))
Example #35
0
def refresh_window(procs, procs_status):
    """Print results on screen by using curses."""
    curses.endwin()
    templ = "%-6s %-8s %4s %6s %6s %5s %5s %9s  %2s"
    win.erase()
    header = templ % ("PID", "USER", "NI", "VIRT", "RES", "CPU%", "MEM%",
                      "TIME+", "NAME")
    print_header(procs_status, len(procs))
    print_line("")
    print_line(header, highlight=True)
    for p in procs:
        # TIME+ column shows process CPU cumulative time and it
        # is expressed as: "mm:ss.ms"
        if p.dict['cpu_times'] is not None:
            ctime = datetime.timedelta(seconds=sum(p.dict['cpu_times']))
            ctime = "%s:%s.%s" % (ctime.seconds // 60 % 60,
                                  str((ctime.seconds % 60)).zfill(2),
                                  str(ctime.microseconds)[:2])
        else:
            ctime = ''
        if p.dict['memory_percent'] is not None:
            p.dict['memory_percent'] = round(p.dict['memory_percent'], 1)
        else:
            p.dict['memory_percent'] = ''
        if p.dict['cpu_percent'] is None:
            p.dict['cpu_percent'] = ''
        if p.dict['username']:
            username = p.dict['username'][:8]
        else:
            username = ""
        line = templ % (p.pid,
                        username,
                        p.dict['nice'],
                        bytes2human(getattr(p.dict['memory_info'], 'vms', 0)),
                        bytes2human(getattr(p.dict['memory_info'], 'rss', 0)),
                        p.dict['cpu_percent'],
                        p.dict['memory_percent'],
                        ctime,
                        p.dict['name'] or '',
                        )
        try:
            print_line(line)
        except curses.error:
            break
        win.refresh()
Example #36
0
def refresh():
    global last
    disk = bytes2human(disk_usage('/').free)
    ip = gethostbyname(gethostname())
    try:
        ssid = check_output("iwgetid -r", shell=True).strip().decode("utf-8")
        ssid = "(%s)" % ssid
    except Exception:
        ssid = "None"
    battery = sensors_battery()
    percent = int(battery.percent) if battery else 0
    status = ["Discharging", "Charging"]
    status = status[battery.power_plugged] if battery else "Unknown"
    if percent in (15, 10, 5) and status == 'Discharging' and percent != last:
        run(["notify-send", "Battery Low!"])
        last = percent
    date = datetime.now().strftime('%h %d %A %H:%M')
    format = "Space: %s | Internet: %s %s | Battery: %s%% %s | Date: %s"
    format = " %s " % format
    write(format % (disk, ip, ssid, percent, status, date))
Example #37
0
def refresh_window(tot_before, tot_after, pnic_before, pnic_after):
    """Print stats on screen."""
    global lineno

    # totals
    print_line("total bytes:           sent: %-10s   received: %s" % (
        bytes2human(tot_after.bytes_sent),
        bytes2human(tot_after.bytes_recv))
    )
    print_line("total packets:         sent: %-10s   received: %s" % (
        tot_after.packets_sent, tot_after.packets_recv))

    # per-network interface details: let's sort network interfaces so
    # that the ones which generated more traffic are shown first
    print_line("")
    nic_names = list(pnic_after.keys())
    nic_names.sort(key=lambda x: sum(pnic_after[x]), reverse=True)
    for name in nic_names:
        stats_before = pnic_before[name]
        stats_after = pnic_after[name]
        templ = "%-15s %15s %15s"
        print_line(templ % (name, "TOTAL", "PER-SEC"), highlight=True)
        print_line(templ % (
            "bytes-sent",
            bytes2human(stats_after.bytes_sent),
            bytes2human(
                stats_after.bytes_sent - stats_before.bytes_sent) + '/s',
        ))
        print_line(templ % (
            "bytes-recv",
            bytes2human(stats_after.bytes_recv),
            bytes2human(
                stats_after.bytes_recv - stats_before.bytes_recv) + '/s',
        ))
        print_line(templ % (
            "pkts-sent",
            stats_after.packets_sent,
            stats_after.packets_sent - stats_before.packets_sent,
        ))
        print_line(templ % (
            "pkts-recv",
            stats_after.packets_recv,
            stats_after.packets_recv - stats_before.packets_recv,
        ))
        print_line("")
    win.refresh()
    lineno = 0
Example #38
0
def run(pid, verbose=False):
    try:
        proc = psutil.Process(pid)
        pinfo = proc.as_dict(ad_value=ACCESS_DENIED)
    except psutil.NoSuchProcess as err:
        sys.exit(str(err))

    # collect other proc info
    with proc.oneshot():
        try:
            parent = proc.parent()
            if parent:
                parent = '(%s)' % parent.name()
            else:
                parent = ''
        except psutil.Error:
            parent = ''
        try:
            pinfo['children'] = proc.children()
        except psutil.Error:
            pinfo['children'] = []
        if pinfo['create_time']:
            started = datetime.datetime.fromtimestamp(
                pinfo['create_time']).strftime('%Y-%m-%d %H:%M')
        else:
            started = ACCESS_DENIED

    # here we go
    print_('pid', pinfo['pid'])
    print_('name', pinfo['name'])
    print_('parent', '%s %s' % (pinfo['ppid'], parent))
    print_('exe', pinfo['exe'])
    print_('cwd', pinfo['cwd'])
    print_('cmdline', ' '.join(pinfo['cmdline']))
    print_('started', started)

    cpu_tot_time = datetime.timedelta(seconds=sum(pinfo['cpu_times']))
    cpu_tot_time = "%s:%s.%s" % (
        cpu_tot_time.seconds // 60 % 60,
        str((cpu_tot_time.seconds % 60)).zfill(2),
        str(cpu_tot_time.microseconds)[:2])
    print_('cpu-tspent', cpu_tot_time)
    print_('cpu-times', str_ntuple(pinfo['cpu_times']))
    if hasattr(proc, "cpu_affinity"):
        print_("cpu-affinity", pinfo["cpu_affinity"])
    if hasattr(proc, "cpu_num"):
        print_("cpu-num", pinfo["cpu_num"])

    print_('memory', str_ntuple(pinfo['memory_info'], convert_bytes=True))
    print_('memory %', round(pinfo['memory_percent'], 2))
    print_('user', pinfo['username'])
    if psutil.POSIX:
        print_('uids', str_ntuple(pinfo['uids']))
    if psutil.POSIX:
        print_('uids', str_ntuple(pinfo['uids']))
    if psutil.POSIX:
        print_('terminal', pinfo['terminal'] or '')

    print_('status', pinfo['status'])
    print_('nice', pinfo['nice'])
    if hasattr(proc, "ionice"):
        try:
            ionice = proc.ionice()
        except psutil.Error:
            pass
        else:
            if psutil.WINDOWS:
                print_("ionice", ionice)
            else:
                print_("ionice", "class=%s, value=%s" % (
                    str(ionice.ioclass), ionice.value))

    print_('num-threads', pinfo['num_threads'])
    if psutil.POSIX:
        print_('num-fds', pinfo['num_fds'])
    if psutil.WINDOWS:
        print_('num-handles', pinfo['num_handles'])

    if 'io_counters' in pinfo:
        print_('I/O', str_ntuple(pinfo['io_counters'], convert_bytes=True))
    if 'num_ctx_switches' in pinfo:
        print_("ctx-switches", str_ntuple(pinfo['num_ctx_switches']))
    if pinfo['children']:
        template = "%-6s %s"
        print_("children", template % ("PID", "NAME"))
        for child in pinfo['children']:
            try:
                print_('', template % (child.pid, child.name()))
            except psutil.AccessDenied:
                print_('', template % (child.pid, ""))
            except psutil.NoSuchProcess:
                pass

    if pinfo['open_files']:
        print_('open-files', 'PATH')
        for i, file in enumerate(pinfo['open_files']):
            if not verbose and i >= NON_VERBOSE_ITERATIONS:
                print_("", "[...]")
                break
            print_('', file.path)
    else:
        print_('open-files', '')

    if pinfo['connections']:
        template = '%-5s %-25s %-25s %s'
        print_('connections',
               template % ('PROTO', 'LOCAL ADDR', 'REMOTE ADDR', 'STATUS'))
        for conn in pinfo['connections']:
            if conn.type == socket.SOCK_STREAM:
                type = 'TCP'
            elif conn.type == socket.SOCK_DGRAM:
                type = 'UDP'
            else:
                type = 'UNIX'
            lip, lport = conn.laddr
            if not conn.raddr:
                rip, rport = '*', '*'
            else:
                rip, rport = conn.raddr
            print_('', template % (
                type,
                "%s:%s" % (lip, lport),
                "%s:%s" % (rip, rport),
                conn.status))
    else:
        print_('connections', '')

    if pinfo['threads'] and len(pinfo['threads']) > 1:
        template = "%-5s %12s %12s"
        print_('threads', template % ("TID", "USER", "SYSTEM"))
        for i, thread in enumerate(pinfo['threads']):
            if not verbose and i >= NON_VERBOSE_ITERATIONS:
                print_("", "[...]")
                break
            print_('', template % thread)
        print_('', "total=%s" % len(pinfo['threads']))
    else:
        print_('threads', '')

    if hasattr(proc, "rlimit"):
        res_names = [x for x in dir(psutil) if x.startswith("RLIMIT")]
        resources = []
        for res_name in res_names:
            try:
                soft, hard = proc.rlimit(getattr(psutil, res_name))
            except psutil.AccessDenied:
                pass
            else:
                resources.append((res_name, soft, hard))
        if resources:
            template = "%-12s %15s %15s"
            print_("res-limits", template % ("RLIMIT", "SOFT", "HARD"))
            for res_name, soft, hard in resources:
                if soft == psutil.RLIM_INFINITY:
                    soft = "infinity"
                if hard == psutil.RLIM_INFINITY:
                    hard = "infinity"
                print_('', template % (
                    RLIMITS_MAP.get(res_name, res_name), soft, hard))

    if hasattr(proc, "environ") and pinfo['environ']:
        template = "%-25s %s"
        print_("environ", template % ("NAME", "VALUE"))
        for i, k in enumerate(sorted(pinfo['environ'])):
            if not verbose and i >= NON_VERBOSE_ITERATIONS:
                print_("", "[...]")
                break
            print_("", template % (k, pinfo['environ'][k]))

    if pinfo.get('memory_maps', None):
        template = "%-8s %s"
        print_("mem-maps", template % ("RSS", "PATH"))
        maps = sorted(pinfo['memory_maps'], key=lambda x: x.rss, reverse=True)
        for i, region in enumerate(maps):
            if not verbose and i >= NON_VERBOSE_ITERATIONS:
                print_("", "[...]")
                break
            print_("", template % (bytes2human(region.rss), region.path))
Example #39
0
def pprint_ntuple(nt):
    for name in nt._fields:
        value = getattr(nt, name)
        if name != 'percent':
            value = bytes2human(value)
        print('%-10s : %7s' % (name.capitalize(), value))