Python学习之十六

首先: 最开始三行的作用是指定运行脚本解析器, 以及编码和需要的os包.
#!/usr/bin/python3

coding=utf-8

import os 其次: 一个命令获取机器列表
vmlist = os.popen(“virsh list |grep -v Id |grep running |awk ‘{print \(2}&#39;&#34;)<br/> 需要注意 os.system() 会直接界面化执行命令, 并不能够返回结果, 需要使用 popen 的方式才能够获取 再次: 建议循环:<br/> for i in vmlist : 循环内处理:<br/> print(i[:-1] + &#34; 机器的IP地址为: &#34;,end=&#34;&#34;)<br/> 通过[:-1] 去掉最后一个回车字符, 通过指定 end=&#34;&#34;, 不能行默认换行, 便于友好展示.<br/> with os.popen(&#34;virsh dumpxml &#34; + i[:-1] + &#34; |grep &#39;mac address&#39;| awk -F \\&#39; &#39;{ print \)2}’”) as pipe :

mac = pipe.read()<br/>

通过 with as 命令, 将 popen 打开的命令结果集转为pipe
然后通过 read 命令, 将结果转换为字符, 不然会报对象未封装的错误. 注意 shell 命令与linux的命令是一样的.