python的100个实例004-获取系统信息

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import psutil
from datetime import datetime
print("CPU逻辑核心数:", psutil.cpu_count()) # CPU逻辑数量
print("CPU时间分配:", psutil.cpu_times()) # CPU用户/系统/空闲时间
print("\n")
print("CPU使用率信息:")
# 循环2次输出 cpu使用率
for x in range(2):
print(datetime.now(), "CPU使用率", psutil.cpu_percent(interval=1, percpu=True))
print("\n")
print("内存信息:", psutil.virtual_memory())
print("交换空间信息:", psutil.swap_memory())
print("\n")
print("磁盘分区信息", psutil.disk_partitions())
print("\n")
for par in psutil.disk_partitions():
print("分区: %s, 使用情况: %s" %
(par.mountpoint, psutil.disk_usage(par.mountpoint)))
print("磁盘IO情况: ", psutil.disk_io_counters())
print("\n")
print("网络IO情况: ", psutil.net_io_counters())
print("\n")
print("网络接口情况: ", psutil.net_if_addrs())
print("\n")
print("网络接口状态: ", psutil.net_if_stats())
print("\n")
print("网络连接信息: ")
for conn in psutil.net_connections():
print("pid=%d, status: %s, localNetInfo: %s, remoteNetInfo: %s" % (
conn.pid, conn.laddr, conn.raddr, conn.status))
print("\n")
print("所有进程ID:", psutil.pids())
p = psutil.Process(17760)
print("进程名称: ", p.name())
print("进程exe路径:", p.exe())
print("进程工作目录:", p.cwd())
print("进程启动的命令行:", p.cmdline())
print("父进程ID:", p.ppid())
print("父进程:", p.parent())
print("子进程列表:", p.children())
print("进程状态:", p.status())
print("进程用户名:", p.username())
print("进程创建时间:", p.create_time())
# print("进程终端:", p.terminal())
print("进程使用的CPU时间:", p.cpu_times())
print("进程使用的内存:", p.memory_info())
print("进程打开的文件:", p.open_files())
print("进程相关网络连接:", p.connections())
print("进程的线程数量:", p.num_threads())
print("所有线程信息:", p.threads())
print("进程环境变量:", p.environ())
print("结束进程", p.terminate())

output:

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
CPU逻辑核心数: 4
CPU时间分配: scputimes(user=10930.375, system=7108.0, idle=102377.046875, interrupt=390.5625, dpc=324.125)
CPU使用率信息:
2018-01-28 00:21:45.278782 CPU使用率 [34.8, 18.8, 26.6, 23.4]
2018-01-28 00:21:46.281749 CPU使用率 [36.2, 15.6, 23.4, 29.7]
内存信息: svmem(total=10251116544, available=4278272000, percent=58.3, used=5972844544, free=4278272000)
交换空间信息: sswap(total=12532817920, used=9507274752, free=3025543168, percent=75.9, sin=0, sout=0)
磁盘分区信息 [sdiskpart(device='C:\\', mountpoint='C:\\', fstype='NTFS', opts='rw,fixed'), sdiskpart(device='D:\\', mountpoint='D:\\', fstype='FAT32', opts='rw,fixed'), sdiskpart(device='E:\\', mountpoint='E:\\', fstype='NTFS', opts='rw,fixed'), sdiskpart(device='F:\\', mountpoint='F:\\', fstype='NTFS', opts='rw,fixed'), sdiskpart(device='G:\\', mountpoint='G:\\', fstype='NTFS', opts='rw,fixed')]
分区: C:\, 使用情况: sdiskusage(total=126590787584, used=89791541248, free=36799246336, percent=70.9)
分区: D:\, 使用情况: sdiskusage(total=53664022528, used=25191579648, free=28472442880, percent=46.9)
分区: E:\, 使用情况: sdiskusage(total=10735316992, used=5701107712, free=5034209280, percent=53.1)
分区: F:\, 使用情况: sdiskusage(total=107374178304, used=67419734016, free=39954444288, percent=62.8)
分区: G:\, 使用情况: sdiskusage(total=68251807744, used=40469872640, free=27781935104, percent=59.3)
磁盘IO情况: sdiskio(read_count=345740, write_count=419470, read_bytes=14608027136, write_bytes=9526425600, read_time=485, write_time=612)
网络IO情况: snetio(bytes_sent=2280626501, bytes_recv=1131084766, packets_sent=2080406, packets_recv=2057105, errin=0, errout=0, dropin=0, dropout=0)
网络接口情况: {'本地连接* 2': [snic(family=<AddressFamily.AF_LINK: -1>, address='xx-xxC2-xx-B6-AE-xx', netmask=None, broadcast=None, ptp=None), snic(family=<AddressFamily.AF_INET: 2>, address='xx.xx.xx.xx', netmask='xx.xx.0.0'...
网络接口状态: {'以太网': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=100, mtu=1500), '蓝牙网络连接': snicstats(isup=False, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=3, mtu=1500), '以太网 2': snicstats(isup=False, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=10, mtu=1400), 'Loopback Pseudo-Interface 1': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=1073, mtu=1500), 'WLAN': snicstats(isup=False, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=300, mtu=1500), '本地连接* 2': snicstats(isup=False, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=0, mtu=1500), 'Teredo Tunneling Pseudo-Interface': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=0, mtu=1472)}
网络连接信息:
pid=3972, status: addr(ip='192.xx.1.xx', port=65361), localNetInfo: addr(ip='xx.215.xx.69', port=443), remoteNetInfo: CLOSE_WAIT
pid=900, status: addr(ip='192.xx.1.xx', port=56517), localNetInfo: addr(ip='xx.43.xx.29', port=443), remoteNetInfo: CLOSE_WAIT
...
所有进程ID: [0, 4, 392, 560, 636, 644, 744,....]
进程名称: EXCEL.EXE
进程exe路径: C:\Program Files (x86)\Microsoft Office\root\Office16\EXCEL.EXE
进程工作目录: C:\Users\xx\Documents
进程启动的命令行: ['C:\\Program Files (x86)\\Microsoft Office\\root\\Office16\\EXCEL.EXE']
父进程ID: 5800
父进程: psutil.Process(pid=5800, name='QMStartMenuPanel64.exe', started='19:09:33')
子进程列表: []
进程状态: running
进程用户名: xx\xx
进程创建时间: 1517069903.0
进程使用的CPU时间: pcputimes(user=9.6875, system=5.96875, children_user=0.0, children_system=0.0)
进程使用的内存: pmem(rss=121597952, vms=70000640, num_page_faults=66660, peak_wset=167497728, wset=121597952, peak_paged_pool=1226464, paged_pool=1164456, peak_nonpaged_pool=181312, nonpaged_pool=68256, pagefile=70000640, peak_pagefile=125423616, private=70000640)
进程打开的文件: [popenfile(path='C:\\Windows\\SysWOW64\\zh-CN\\crypt32.dll.mui', fd=-1), ...
进程相关网络连接: []
进程的线程数量: 30
所有线程信息: [pthread(id=17520, user_time=2.765625, system_time=3.703125),...]
进程环境变量: {'ALLUSERSPROFILE': 'C:\\ProgramData', 'APPDATA': ....
结束进程 None

python的100个实例003-处理http请求

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
import requests
print("*****************一般性Http请求*******************")
# http请求
r = requests.get('https://www.baidu.com/')
print('HttpStatus:%d' %(r.status_code))
print('Encoding:%s' %(r.encoding))
# 无论响应是文本还是二进制内容,我们都可以用content属性获得bytes对象:
print(r.content)
print("*****************JSON获取*******************")
# 对于特定类型的响应,例如JSON,可以直接获取
r = requests.get('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20%3D%202151330&format=json')
print(r.json())
print("*****************传入特殊请求头*****************")
r = requests.get('https://www.douban.com/', headers={'User-Agent':
'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit'})
print(r.text) # 输出手机版的网页
print("*****************发送POST请求*****************")
r = requests.post('https://accounts.douban.com/login',
data={'form_email': 'abc@example.com', 'form_password': '123456'})
print(r.text)
print("*****************发送JSON请求*****************")
params = {'key': 'value'}
cookieStr = {'JSESSIONID': '098'}
# 内部自动序列化为JSON
r = requests.post("url", json=params, cookies=cookieStr, timeout=5)
print(r.headers)
activityInfo =r.json()
# 可直接获取对象属性
print(activityInfo['res_data'][-1]['name'])