dextervip dextervip - 1 month ago 20
Python Question

How to run cmd windows netsh command using python?

I am trying to run the following netsh command on Windows 7 however It returns incorrect syntax

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
>>>


What's wrong?

Answer

os.systemis a very old choice and not really recommended.

Instead you should consider subprocess.call() or subprocess.Popen().

Here is how to use them:

If you don't care about the output, then:

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

If you do care about the output, then:

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