How to run cmd windows netsh command using python?

后端 未结 1 1359
情深已故
情深已故 2021-01-14 22:35

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          


        
相关标签:
1条回答
  • 2021-01-14 23:05

    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
    
    0 讨论(0)
提交回复
热议问题