如何使用python运行cmd Windows netsh命令?


问题内容

我正在尝试在Windows 7上运行以下netsh命令,但返回的语法错误

Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.system("netsh interface ipv4 set interface ""Conexão de Rede sem Fio"" metric=1")
The syntax of the file name, directory name or volume label is incorrect.


1
>>>

怎么了?


问题答案:

os.system是一个非常古老的选择,不建议使用。

相反,您应该考虑subprocess.call()subprocess.Popen()

使用方法如下:

如果您不关心输出,则:

import subprocess
...
subprocess.call('netsh interface ipv4 set interface ""Wireless Network" metric=1', shell=True)

如果您确实关心输出,则:

netshcmd=subprocess.Popen('netsh interface ipv4 set interface ""Wireless Network" metric=1', shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE )
output, errors =  netshcmd.communicate()
if errors: 
   print "WARNING: ", errors
 else:
   print "SUCCESS ", output