2012-09-12 81 views
2

我試圖在Windows 7上運行以下netsh命令然而,返回不正確的語法如何使用python運行cmd windows 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 
>>> 

有什麼不對?

回答

4

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

我再次測試,我看到我的問題是拉丁字符,我刪除它們然後它工作。在使用拉丁字符運行命令時,您是否知道任何問題? – dextervip

+0

嗯......不,通常我在編程時避免使用非ascii字符。出於幾個原因,主要是因爲Windows終端是愚蠢的。 – Oz123

+0

@dextervip,你檢查過你的代碼是否在腳本中工作嗎?在腳本的開頭添加# - * - coding:utf-8 - * - 行。並確保你的編輯器保存這樣的文檔。最後,請嘗試一下我的建議,當你想做複雜的事情時,os.system會再次咬你。 – Oz123