如何使用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 >>> 

怎么了?

Solutions Collecting From Web of "如何使用python运行cmd windows netsh命令?"

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