通过一个例子来探讨交互式环境下输入

来源:互联网 发布:im聊天软件蓝色 编辑:程序博客网 时间:2024/05/17 23:45

有时候需要在子SHELL中输入,从而获取命令的输出,比如说,要获取WINDOWNS下面的UUID,可以

C:\>wmicwmic:root\cli>csproduct list fullDescription=Computer System ProductIdentifyingNumber=CNU416B7ZWName=HP ProBook 640 G1SKUNumber=UUID=DDEA2C7F-21BB-1111-ACD0-6C895404C0FFVendor=Hewlett-PackardVersion=A3008CD10003
先输入wmic命令,再输入csproduct list full命令来获得,其中输入wmic命令后,进去了交互式界面。这个时候使用下面的代码是解决不了问题的。 
import osprint os.system('wmic')print os.system('csproduct list full')wmic:root\cli>
光标会一直停留在wmic:root\cli>等待输入

这个时候,就必须想其他的办法,比如说:将两个命令合二为一,再获取其输出:

>>> import os>>> P = os.popen('wmic csproduct list full')>>> X = P.read()>>> print XDescription=Computer System ProductIdentifyingNumber=CNU416B7ZWName=HP ProBook 640 G1SKUNumber=UUID=DDEA2C7F-21BB-1111-ACD0-6C895404C0FFVendor=Hewlett-PackardVersion=A3008CD10003
或者再加个过滤条件,直接获取UUID

>>> import os>>> P = os.popen('wmic csproduct list full | findstr UUID')>>> X = P.read()>>> UUID = X.split('=')[1]>>> print UUIDDDEA2C7F-21BB-1111-ACD0-6C895404C0FF
如果不将二个命令合二为一,就要直面问题,如何在交互式环境下,输入命令,从而获取结果,这里有个办法,借助subprocess模块来完成,代码如下:

>>> import subprocess>>> rst = subprocess.check_output(['wmic', 'csproduct', 'list', 'full'])>>> print rstDescription=Computer System ProductIdentifyingNumber=CNU416B7ZWName=HP ProBook 640 G1SKUNumber=UUID=DDEA2C7F-21BB-1111-ACD0-6C895404C0FFVendor=Hewlett-PackardVersion=A3008CD10003


原创粉丝点击