当前位置: 首页>>代码示例>>Python>>正文


Python psutil.virtual_memory函数代码示例

本文整理汇总了Python中psutil.virtual_memory函数的典型用法代码示例。如果您正苦于以下问题:Python virtual_memory函数的具体用法?Python virtual_memory怎么用?Python virtual_memory使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了virtual_memory函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: meminfo

def meminfo():
	mem = int((psutil.virtual_memory().active/psutil.virtual_memory().total)*100)
	if mem >= 90:
		return ("MEM: {0}%".format(mem), RED)
	elif mem <= 10:
		return ("MEM: {0}%".format(mem), BLUE)
	else:
		return ("MEM: {0}%".format(mem), GREEN)
开发者ID:Ferus,项目名称:git-home,代码行数:8,代码来源:statusinfo.py

示例2: cpustat

    def cpustat(self):
        tags="node:%s %s"%(self.nodename,self.tags)

        val=int(psutil.cpu_percent())
        measurement="cpu_perc"
        key="%s.%s"%(self.nodename,measurement)
        self.measure(key,measurement,tags,val,aggrkey=measurement)

        val=int(psutil.virtual_memory()[1]/1024/1024)
        measurement="mem_free_mb"
        key="%s.%s"%(self.nodename,measurement)
        self.measure(key,measurement,tags,val,aggrkey=measurement)

        val=int(psutil.swap_memory()[3])
        measurement="mem_virt_perc"
        key="%s.%s"%(self.nodename,measurement)
        self.measure(key,measurement,tags,val,aggrkey=measurement)

        val=int(psutil.virtual_memory()[2])
        measurement="mem_phy_perc"
        key="%s.%s"%(self.nodename,measurement)
        self.measure(key,measurement,tags,val,aggrkey=measurement)

        res=psutil.cpu_times_percent()
        names=["cputimeperc_user","cputimeperc_nice","cputimeperc_system","cputimeperc_idle","cputimeperc_iowait","cputimeperc_irq","cputimeperc_softirq","steal","guest","guest_nice"]
        for i in range(len(names)):
            if names[i].startswith("cputime"):
                val=int(res[i])
                measurement=names[i]
                key="%s.%s"%(self.nodename,measurement)
                self.measure(key,measurement,tags,val,aggrkey=measurement)
开发者ID:gitter-badger,项目名称:jumpscale_core8,代码行数:31,代码来源:MonitorTools.py

示例3: sysinfo

def sysinfo():
    boot_start = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(psutil.boot_time()))
    time.sleep(0.5)
    cpu_usage = psutil.cpu_percent()
    ram = int(psutil.virtual_memory().total / (1027 * 1024))
    ram_percent = psutil.virtual_memory().percent
    swap = int(psutil.swap_memory().total / (1027 * 1024))
    swap_percent = psutil.swap_memory().percent
    net_sent = psutil.net_io_counters().bytes_sent
    net_recv = psutil.net_io_counters().bytes_recv
    net_spkg = psutil.net_io_counters().packets_sent
    net_rpkg = psutil.net_io_counters().packets_recv
    sysinfo_string = ""
    if __name__ == "__main__":
        bfh = r'%'
        print(" \033[1;32m开机时间:%s\033[1;m" % boot_start)
        print(" \033[1;32m当前CPU使用率:%s%s\033[1;m" % (cpu_usage, bfh))
        print(" \033[1;32m物理内存:%dM\t使用率:%s%s\033[1;m" % (ram, ram_percent, bfh))
        print(" \033[1;32mSwap内存:%dM\t使用率:%s%s\033[1;m" % (swap, swap_percent, bfh))
        print(" \033[1;32m发送:%d Byte\t发送包数:%d个\033[1;m" % (net_sent, net_spkg))
        print(" \033[1;32m接收:%d Byte\t接收包数:%d个\033[1;m" % (net_recv, net_rpkg))
        for i in psutil.disk_partitions():
            print(" \033[1;32m盘符: %s 挂载点: %s 使用率: %s%s\033[1;m" % (i[0], i[1], psutil.disk_usage(i[1])[3], bfh))

        sysinfo_string = '开机时间: ' + boot_start + '\n'
        sysinfo_string += '当前CPU使用率: ' + str(cpu_usage) + '%\n'
        sysinfo_string += '物理内存: ' + str(ram) + 'M\t使用率: ' + str(ram_percent) + '%\t'
        sysinfo_string += 'Swap内存: ' + str(swap) + 'M\t使用率: ' + str(swap_percent) + '%\n'
        return sysinfo_string

    else:
        file = open("sysinfo.log", "a")
        file.write("CPU:%s   \tRAM:%s\tnet_recv:%d\tNet_sent:%d\r\n" % (cpu_usage, ram_percent, net_recv, net_sent))
        file.flush()
        file.close()
开发者ID:dong4j,项目名称:dubbo_demo,代码行数:35,代码来源:monitor.py

示例4: Sysinfo

def Sysinfo():  
    Hostname = platform.node()
    Sys_version = platform.platform()
    Boot_Start = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(psutil.boot_time()))    
    time.sleep(0.5)  
    Cpu_usage = psutil.cpu_percent()  
    RAM = int(psutil.virtual_memory().total/(1027*1024))  
    RAM_percent = psutil.virtual_memory().percent  
    Swap = int(psutil.swap_memory().total/(1027*1024))  
    Swap_percent = psutil.swap_memory().percent  
    Net_sent = psutil.net_io_counters().bytes_sent  
    Net_recv = psutil.net_io_counters().bytes_recv  
    Net_spkg = psutil.net_io_counters().packets_sent  
    Net_rpkg = psutil.net_io_counters().packets_recv  
    BFH = r'%'
    print " \033[1;32m主机名: %s\033[1;m" % Hostname  
    print " \033[1;32m系统版本: %s\033[1;m" % Sys_version  
    print " \033[1;32m开机时间:%s\033[1;m"  % Boot_Start  
    print " \033[1;32m当前CPU使用率:%s%s\033[1;m" % (Cpu_usage,BFH)  
    print " \033[1;32m物理内存:%dM\t使用率:%s%s\033[1;m" % (RAM,RAM_percent,BFH)  
    print " \033[1;32mSwap内存:%dM\t使用率:%s%s\033[1;m" % (Swap,Swap_percent,BFH)  
    print " \033[1;32m发送:%d Byte\t发送包数:%d个\033[1;m" % (Net_sent,Net_spkg)  
    print " \033[1;32m接收:%d Byte\t接收包数:%d个\033[1;m" % (Net_recv,Net_rpkg)  
  
    for i in psutil.disk_partitions():  
        print " \033[1;32m盘符: %s 挂载点: %s 使用率: %s%s\033[1;m" % (i[0],i[1],psutil.disk_usage(i[1])[3],BFH)  
    for key in psutil.net_if_addrs().keys():  
        print " \033[1;32m网卡: %s IP: %s\033[1;m" % (key,psutil.net_if_addrs()[key][0][1])  
开发者ID:weady,项目名称:python,代码行数:28,代码来源:python.sys.info.py

示例5: ajax_sysinfo

def ajax_sysinfo():
    sys_info['mem_usage_percent'] = psutil.virtual_memory().percent
    sys_info['mem_total'] = psutil.virtual_memory().total
    sys_info['mem_used'] = psutil.virtual_memory().used
    sys_info['cpu_util'] = psutil.cpu_percent(percpu=True, interval=None)
    #data = jsonify(results=["1", "2", "3"], name="Punit")
    return jsonify(sysinfo=sys_info)
开发者ID:punitsoni,项目名称:flaskr,代码行数:7,代码来源:views.py

示例6: still_checkin

    def still_checkin(self, hostname, ip_addr, port, load, data_dir, status="OK", max_tasks=2, cur_tasks=0):
        ###
        # still_checkin : Check to see if the still entry already exists in the database, if it does update the timestamp, port, data_dir, and load.
        #                 If does not exist then go ahead and create an entry.
        ###
        s = self.Session()

        if s.query(Still).filter(Still.hostname == hostname).count() > 0:  # Check if the still already exists, if so just update the time
            still = s.query(Still).filter(Still.hostname == hostname).one()
            still.last_checkin = datetime.datetime.now()
            still.status = status
            # print("STILL_CHECKIN, test mode, setting load = 0, change back before release")
            # still.current_load = 0
            still.current_load = psutil.cpu_percent()
            still.number_of_cores = psutil.cpu_count()
            still.free_memory = round(psutil.virtual_memory().free / (1024 ** 3), 2)
            still.total_memory = round(psutil.virtual_memory().total / (1024 ** 3), 2)
            still.data_dir = data_dir
            still.port = port
            still.max_num_of_tasks = max_tasks
            still.cur_num_of_tasks = cur_tasks
            s.add(still)
        else:  # Still doesn't exist, lets add it
            still = Still(hostname=hostname, ip_addr=ip_addr, port=port, current_load=load,
                          data_dir=data_dir, status=status, max_num_of_tasks=max_tasks, cur_num_of_tasks=cur_tasks)
            s.add(still)

        s.commit()
        s.close()
        return 0
开发者ID:pkgw,项目名称:hera-real-time-pipe,代码行数:30,代码来源:dbi.py

示例7: CatchMEM

def CatchMEM(RunNumb, Interval, TimeStart):

	"""
	Funzione per catturare i dati della Memoria

	Cattura le percentuali di utilizzo della memoria e della swap medie nell'intervallo richiesto
	 e le impacchetta per formare la risposta.

	:param RunNumb: Il numero della Run corrente (al momento in cui è stato richiesto il lavoro al server)
	:param Interval: Intervallo tra un campionamento e l'altro.
	:param TimeStart: Tempo di avvio di questo campionamento, lo restituisco in uscita per poter calcolare la latenza.
	:returns: Una tupla contenente i dati rilevati nel Interval.
	"""
	#selettori per andare a selezionare la percentuale di memoria utilizzata nelle rispettive liste ritornate da psutil
	SelPerc = 3

	Average_MEM, Average_SWP = 0, 0
	for i in range(Interval):
		#Average_MEM += psutil.phymem_usage()[SelPerc]/(Interval+1)
		#Average_SWP += psutil.virtmem_usage()[SelPerc]/(Interval+1)
		Average_MEM += psutil.virtual_memory().percent/(Interval+1)
		Average_SWP += psutil.swap_memory().percent/(Interval+1)
		time.sleep(1)

	Average_MEM += psutil.virtual_memory().percent/(Interval+1)
	Average_SWP += psutil.swap_memory().percent/(Interval+1)
	ProbeManager.PutResult([ProbeID, RunNumb, "MEM", Average_MEM, Average_SWP, TimeStart])
开发者ID:sb00nk,项目名称:ReMon,代码行数:27,代码来源:Probe.py

示例8: performance

def performance(attribute):
    """ A little smater routing system.
    """

    data = None

    if attribute == 'system':
        data = { 'system': platform.system() }
    elif attribute == 'processor':
        data = { 'processor': platform.processor() }
    elif attribute in ['cpu_count', 'cpucount'] :
        data = { 'cpu_count': psutil.cpu_count() }
    elif attribute == 'machine':
        data = { 'machine': platform.machine() }
    elif attribute in ['virtual_mem', 'virtualmem']:
        data = { 'virtual_mem': psutil.virtual_memory().total }
    elif attribute in ['virtual_mem_gb', 'virtualmemgb']:
        data = { 'virtual_mem_gb': psutil.virtual_memory().total / (1024.0 ** 3) }
    elif attribute == 'all':
        data = {
            'system': platform.system(),
            'processor': platform.processor(),
            'cpu_count': psutil.cpu_count(),
            'machine': platform.machine(),
            'virtual_mem': psutil.virtual_memory().total,
            'virtual_mem_gb': psutil.virtual_memory().total / (1024.0 ** 3),
        }

    packet = json.dumps(data)
    resp = Response(packet, status=200, mimetype='application/json')

    return(resp)
开发者ID:DamienTian,项目名称:hid-sp18-505,代码行数:32,代码来源:run.py

示例9: get_mem_swap

    def get_mem_swap(self,):
        """
        Get memory and swap usage
        """
        try:
            # psutil >= 0.6.0
            phymem = psutil.virtual_memory()
            buffers = psutil.virtual_memory().buffers
            cached = psutil.virtual_memory().cached
            vmem = psutil.swap_memory()
        except AttributeError:
            # psutil > 0.4.0 and < 0.6.0
            phymem = psutil.phymem_usage()
            buffers = getattr(psutil, 'phymem_buffers', lambda: 0)()
            cached = getattr(psutil, 'cached_phymem', lambda: 0)()
            vmem = psutil.virtmem_usage()

        mem_used = phymem.total - (phymem.free + buffers + cached)
        return (
            phymem.percent,
            mem_used,
            phymem.total,
            vmem.percent,
            vmem.used,
            vmem.total)
开发者ID:Adel-Magebinary,项目名称:pg_activity,代码行数:25,代码来源:Data.py

示例10: __init__

    def __init__(self, interval, history_len):
        """

        :param interval: Collect statistics according to this interval.
        :param history_len: Use this many to compute avg/max statistics.
        """

        self.interval = interval
        self.history_len = history_len
        try:
            import psutil  # @UnresolvedImport @Reimport
        except:
            self._available = False
        else:
            self._available = True

            self.cpu = Collect('cpu', lambda: psutil.cpu_percent(interval=0),
                               interval, history_len)

            try:
                # new in 0.8
                psutil.virtual_memory().percent
                get_mem = lambda: psutil.virtual_memory().percent
            except:
                get_mem = lambda: psutil.phymem_usage().percent

            self.mem = Collect('mem', get_mem, interval, history_len)
            try:
                # new in 0.8
                psutil.swap_memory().percent
                get_mem = lambda: psutil.swap_memory().percent
            except:
                get_mem = lambda: psutil.virtmem_usage().percent

            self.swap_mem = Collect('swap', get_mem, interval, history_len)
开发者ID:p-muller,项目名称:compmake,代码行数:35,代码来源:system_stats.py

示例11: getSystemInfo

def getSystemInfo():
	"""
	Get a dictionary with some system/server info

	return -- ["unix", "connectedUsers", "webServer", "cpuUsage", "totalMemory", "usedMemory", "loadAverage"]
	"""

	data = {}

	# Get if server is running under unix/nt
	data["unix"] = runningUnderUnix()

	# General stats
	data["connectedUsers"] = len(glob.tokens.tokens)
	data["webServer"] = glob.conf.config["server"]["server"]
	data["cpuUsage"] = psutil.cpu_percent()
	data["totalMemory"] = "{0:.2f}".format(psutil.virtual_memory()[0]/1074000000)
	data["usedMemory"] = "{0:.2f}".format(psutil.virtual_memory()[3]/1074000000)

	# Unix only stats
	if (data["unix"] == True):
		data["loadAverage"] = os.getloadavg()
	else:
		data["loadAverage"] = (0,0,0)

	return data
开发者ID:Castar,项目名称:ripple,代码行数:26,代码来源:systemHelper.py

示例12: run

 def run(self):
     while self.RUN:
         cpu = psutil.cpu_percent(interval=None)
         ram = (psutil.virtual_memory()[0] - psutil.virtual_memory()[1]) / psutil.virtual_memory()[0] * 100
         
         update_sensors.save_system_reading(cpu, ram)
         time.sleep(settings.how_often_to_check_system)
开发者ID:1n5aN1aC,项目名称:rainmeter-pi,代码行数:7,代码来源:thread_sensors.py

示例13: check_mem

 def  check_mem(self):
   #  meminfo=psutil.virtual_memory()
      mem_total=psutil.virtual_memory().total
      mem_free=psutil.virtual_memory().free
  #    mem_free_percent= float(  "%.2f" % (float(mem_free)/float(mem_total))  )
      mem_free_percent= float(  "%.1f" % (float(mem_free)/float(mem_total) *100 )  )
      meminfo=[mem_total,mem_free,mem_free_percent]
      return  meminfo
开发者ID:251871553,项目名称:monitorserver,代码行数:8,代码来源:monitorclient.py

示例14: __init__

 def __init__(self):
     super(NumpyDevice, self).__init__()
     self.device_info = DeviceInfo(
         desc="Python Numpy", memsize=virtual_memory().total,
         memalign=8, version=numpy.__version__,
         device_type="Hybrid",
         max_work_group_size=None, max_work_item_sizes=None,
         local_memsize=virtual_memory().total)
开发者ID:EgBulychev,项目名称:veles,代码行数:8,代码来源:backends.py

示例15: memInfo

    def memInfo(self):
        mem={"total":'', "used":'', "threshhold":False}
        mem['total'] = psutil.virtual_memory().total
        mem['used'] = psutil.virtual_memory().used

        if (mem['total'] - mem['used']) <= conf.memLimit:
            mem["threshhold"]=True
        return mem
开发者ID:hoonkim,项目名称:Lesser,代码行数:8,代码来源:controller.py


注:本文中的psutil.virtual_memory函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。