what's the psutil模块

what's the psutil模块

  psutil 是一个跨平台库,能够轻松实现获取系统运行的进程和系统利用率(包括CPU、内存、磁盘、网络等)信息。它主要用来做系统监控,性能分析,进程管理。它实现了同等命令行工具提供的功能,如 ps、top、lsof、netstat、ifconfig、who、df、kill、free、nice、ionice、iostat、iotop、uptime、pidof、tty、taskset、pmap 等。目前支持 32 位和 64 位的 Linux、Windows、OS X、FreeBSD 和 Sun Solaris 等操作系统.

  这里研究 Python 的 psutil 库

 

安装

pip insatll psutil

 

获取系统信息

1.CPU信息

# 使用 cpu_times 方法获取 cpu 的完整信息,如下所示。
psutil.cpu_times()
# scputimes(user=650613.02, nice=22.14, system=154916.5, idle=16702285.26, iowait=68894.55, irq=3.38, softirq=7075.65, steal=0.0, guest=0.0)

# 获取单个数据,如用户的cpu时或io等待时间,如下所示:
psutil.cpu_times().user # 650617.11
psutil.cpu_times().iowait # 68894.63

# 获取cpu逻辑和物理个数,默认logical值为True 。

#CPU逻辑个数
psutil.cpu_count() # 2
#CPU物理个数
psutil.cpu_count(logical=False) # 1
# 获取cpu的使用率:
psutil.cpu_percent() # 2.5
psutil.cpu_percent(1) # 2.5

 

2.内存信息

  内存信息的获取主要使用 virtual_memory 方法。swap 使用就用 swap_memory 方法。

mem = psutil.virtual_memory()
print(mem)
# svmem(total=4018601984, available=1066205184, percent=73.5, used=3904004096, free=114597888, active=3302174720, inactive=426078208, buffers=156520448, cached=795086848)
mem.total # 4018601984
mem.used # 3904004096
mem.free # 114597888
print(mem.total/1024/1024) # 3832.4375
# 其中percent表示实际已经使用的内存占比,即(1047543808-717537280)/1047543808*100% 。available表示还可以使用的内存。

 

 3.磁盘信息

  磁盘信息主要有两部分,一个是磁盘的利用率,一个是 io,他们分别可以通过 disk_usage 和 disk_io_counters 方法获取。

如下先获取分区信息,然后看下根分区的使用情况:

psutil.disk_partitions()
# [sdiskpart(device='/dev/mapper/root', mountpoint='/', fstype='ext4', opts='rw,errors=remount-ro'), sdiskpart(device='/dev/sda1', mountpoint='/boot', fstype='ext2', opts='rw')]
psutil.disk_usage('/')
# sdiskusage(total=42273669120, used=17241096192, free=22885195776, percent=40.8)

# 默认disk_io_counters方法获取的是硬盘总的io数和读写信息,如果需要获取单个分区的io和读写信息加上"perdisk=True"参数。

psutil.disk_io_counters()
# sdiskio(read_count=638190, write_count=77080153, read_bytes=16037795840, write_bytes=1628871606272, read_time=2307367, write_time=1777841305)
psutil.disk_io_counters(perdisk=True)
# {'vdb1': sdiskio(read_count=312, write_count=0, read_bytes=1238016, write_bytes=0, read_time=95, write_time=0), 'vda1': sdiskio(read_count=637878, write_count=77080257, read_bytes=16036557824, write_bytes=1628873314304, read_time=2307272, write_time=1777841879)}

 

4.网络信息:

  网络 io 和磁盘 io 使用方法差不多,主要使用 net_io_counters 方法,如果需要获取单个网卡的 io 信息,加上 pernic=True 参数。

#获取网络总的io情况
psutil.net_io_counters()
# snetio(bytes_sent=525490132009, bytes_recv=409145642892, packets_sent=948527563, packets_recv=778182181, errin=0, errout=0, dropin=0, dropout=0)
#获取网卡的io情况
psutil.net_io_counters(pernic=True)
# {'lo': snetio(bytes_sent=56524704027, bytes_recv=56524704027, packets_sent=33602236, packets_recv=33602236, errin=0, errout=0, dropin=0, dropout=0), 'eth0': snetio(bytes_sent=468966480940, bytes_recv=352622081327, packets_sent=914930488, packets_recv=744583332, errin=0, errout=0, dropin=0, dropout=0)}

 

5.其他系统信息:

# 1.获取开机时间
##以linux时间格式返回,可以使用时间戳转换
psutil.boot_time() # 1496647567.0

#转换成自然时间格式
psutil.boot_time() # 1496647567.0
datetime.datetime.fromtimestamp(psutil.boot_time ()).strftime("%Y-%m-%d %H: %M: %S") # '2017-06-05 15: 26: 07'


# 2.查看系统全部进程
psutil.pids()
'''
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 
31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 46, 47, 48, 49, 50, 51, 52, 53, 60, 61, 63, 64, 65, 97, 98,
279, 280, 331, 398, 481, 676, 693, 769, 845, 848, 1023, 1085, 1108, 1355, 1366, 1457, 1474, 1475, 1494, 1541,
1543, 1545, 1546, 1548, 1550, 1552, 2829, 12436, 12913, 13129, 16022, 16029, 16030, 16031, 16032, 16033, 16518,
16520, 17088, 17124, 19203, 25382, 32679]
''' # 3.查看单个进程 p = psutil.Process(16031) p.name() #进程名 p.exe() #进程的bin路径 p.cwd() #进程的工作目录绝对路径 p.status() #进程状态 p.create_time() #进程创建时间 p.uids() #进程uid信息 p.gids() #进程的gid信息 p.cpu_times() #进程的cpu时间信息,包括user,system两个cpu信息 p.cpu_affinity() #get进程cpu亲和度,如果要设置cpu亲和度,将cpu号作为参考就好 p.memory_percent() #进程内存利用率 p.memory_info() #进程内存rss,vms信息 p.io_counters() #进程的IO信息,包括读写IO数字及参数 p.connectios() #返回进程列表 p.num_threads() #进程开启的线程数 听过psutil的Popen方法启动应用程序,可以跟踪程序的相关信息 from subprocess import PIPE p = psutil.Popen(["/usr/bin/python", "-c", "print('hello')"],stdout=PIPE) p.name() p.username()

 

 

 

 

 

 

      

转载于:https://www.cnblogs.com/zhuminghui/p/11347461.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Sure, here's an example code in Python using scikit-learn library to classify iris data using logistic regression: ``` from sklearn.datasets import load_iris from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score # Load the iris dataset iris = load_iris() # Split the dataset into training and testing sets X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3, random_state=42) # Preprocess the data by scaling the features scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) # Train a logistic regression model on the training set lr = LogisticRegression(penalty='l2', C=1.0, solver='lbfgs', max_iter=1000) lr.fit(X_train, y_train) # Evaluate the performance of the model on the testing set y_pred = lr.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print("Accuracy: %.2f%%" % (accuracy * 100.0)) ``` In this code, we first load the iris dataset using `load_iris` function from scikit-learn library. We then split the data into training and testing sets using `train_test_split` function. We use `StandardScaler` from scikit-learn to scale the input features to have zero mean and unit variance. We then train a logistic regression model using `LogisticRegression` class from scikit-learn library with `penalty='l2'` for L2 regularization, `C=1.0` for regularization strength, `solver='lbfgs'` for optimization algorithm, and `max_iter=1000` for maximum number of iterations. Finally, we use `accuracy_score` function from scikit-learn to evaluate the performance of the model on the testing set.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值