数据库都是用来插入,删除,检索数据的,比如你要做的一个产品,一定程度上对于体系结构,CPU NUMA等要求比较高,为了保持可移植性,对于不同的机器,需要预先读取机器CPU的相关信息;假如想将下面信息每行以key和value保存到redis中
[lihui@localhost ~]# lscpu Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Byte Order: Little Endian CPU(s): 12 On-line CPU(s) list: 0-11 Thread(s) per core: 1 Core(s) per socket: 6 Socket(s): 2 NUMA node(s): 2 Vendor ID: GenuineIntel CPU family: 6 Model: 44 Stepping: 2 CPU MHz: 1596.000 BogoMIPS: 5066.54 Virtualization: VT-x L1d cache: 32K L1i cache: 32K L2 cache: 256K L3 cache: 12288K NUMA node0 CPU(s): 0,2,4,6,8,10 NUMA node1 CPU(s): 1,3,5,7,9,11
这里的输出信息格式已经非常标准了,冒号左右两边可以当作是key和value插入到redis,因此只要将他们分别拔出来就行了,这里数据信息不大,就不考虑程序性能了
[lihui@localhost ~]# cat cpu.py #!/usr/bin/env python import os import redis import re pattern = '(.*):\s+(.*)' r = redis.StrictRedis(host = 'localhost', port = 6379, db = 0) pf = os.popen('lscpu') for eachLine in pf: eachLine = eachLine.strip() info = re.match(pattern, eachLine) if info is not None: r.set(info.group(1), info.group(2))
假如你对正则表达式没有好感,或者是性能方面的考虑,可以通过split来进行,由于这里只需要通过冒号来分割,就十分容易了,但是要注意的是,分割之后,我们需要的有效字符串可能左右两边存在空格,因此在插入数据库之前将空格清除
#!/usr/bin/env python import os import redis #import re #pattern = '(.*):\s+(.*)' r = redis.StrictRedis(host = 'localhost', port = 6379, db = 0) pf = os.popen('lscpu') for eachLine in pf: eachLine = eachLine.strip() array = eachLine.split(':') r.set(array[0].strip(), array[1].strip())
由于哈希是无序了,所以最终dump出来的信息与命令结果顺序不一致请不要惊讶,key和value的索引方式,只需要知道key即可,方便快捷,至于key的相对关系,无伤大雅
这里仅仅插入了string的值,至于其它数据类型,换汤不换药
[lihui@localhost ~]# ./cpu.py [lihui@localhost ~]# /usr/local/bin/redis-cli 127.0.0.1:6379> keys * 1) "Virtualization" 2) "NUMA node1 CPU(s)" 3) "CPU(s)" 4) "Model" 5) "Socket(s)" 6) "L3 cache" 7) "NUMA node(s)" 8) "Vendor ID" 9) "CPU family" 10) "L1d cache" 11) "CPU MHz" 12) "Byte Order" 13) "Stepping" 14) "On-line CPU(s) list" 15) "Architecture" 16) "BogoMIPS" 17) "CPU op-mode(s)" 18) "L1i cache" 19) "Thread(s) per core" 20) "NUMA node0 CPU(s)" 21) "Core(s) per socket" 22) "L2 cache" 127.0.0.1:6379> get CPU(s) "12" 127.0.0.1:6379> get NUMA node0 CPU(s) (error) ERR wrong number of arguments for 'get' command 127.0.0.1:6379> get 'NUMA node0 CPU(s)' "0,2,4,6,8,10" 127.0.0.1:6379>