如何使用python解析netsh输出

时间:2016-11-04 16:58:28

标签: python subprocess netsh

我正在使用以下方式获得输出:

  

import subprocess x = subprocess.call('netsh interface show   界面')

as

Admin State    State          Type             Interface Name
-------------------------------------------------------------------------
Enabled        Connected      Dedicated        Ethernet0

但是在尝试解析netsh输出时如下:

  

x.split()   引发错误“AttributeError:'int'对象没有属性'split'”我厌倦了其他几种方式,但没有奏效。

我正在尝试使用python从netsh输出中检索(过滤)接口名称。

1 个答案:

答案 0 :(得分:1)

$pattern = '/(?<=href\="|\')([^"\']+)(?="|\')/m'; $new_string = preg_replace_callback($pattern, function ($matches) { return isset($matches[1]) ? url_to_postid($matches[1]) : $matches[0]; }, $string); 只返回返回码,而不是命令的输出流。

要做你想做的事,你可以这样做:

subprocess.call

然后p = subprocess.Popen('netsh interface show interface',stdout=subprocess.PIPE) [x,err] = p.communicate() 包含x程序提供的输出。

作为一般性评论,请注意最好将参数传递给字符串,如下所示:

netsh

所以你可以更好地控制参数,并且可以在其中传递带空格的参数,而无需引用它们,引用由['netsh','interface','show','interface'] 模块完成。