【问题标题】:How to run cmd windows netsh command using python?如何使用 python 运行 cmd windows netsh 命令?
【发布时间】:2012-09-12 05:31:13
【问题描述】:

我正在尝试在 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
>>>

怎么了?

【问题讨论】:

    标签: python windows


    【解决方案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
    

    【讨论】:

    • 我再次测试,我发现我的问题是拉丁字符,我删除了它们然后它工作了。你知道在运行带有拉丁字符的命令时有什么问题吗?
    • hmm ... 不,通常我在编程中避免使用非 ascii 字符。出于几个原因,主要是因为 Windows 终端是愚蠢的。
    • @dextervip,您是否检查过您的代码是否在脚本中工作?在脚本的开头添加 # -- coding: utf-8 -- 行。并确保您的编辑器像这样保存文档。最后,请尝试一下我的建议,当你想做复杂的事情时,os.system 会再次咬你。
    • 好吧,我将使用非 ascii 字符,谢谢 :)
    猜你喜欢
    • 1970-01-01
    • 2011-07-12
    • 2019-06-28
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    • 2015-01-15
    • 2023-03-17
    • 2018-03-14
    相关资源
    最近更新 更多