【问题标题】:Python running ping and getting the exit codePython 运行 ping 并获取退出代码
【发布时间】:2014-03-03 12:19:08
【问题描述】:

我正在尝试通过 python 脚本 ping 主机,并捕获 ping 的输出和退出代码。为此我想出了以下python sn-p:

ping_command = "ping -c 5 -n -W 4 " + IP
ping_process = os.popen(ping_command)
ping_output = ping_process.read()
exit_code_ping = ping_process.close()
exit_code = os.WEXITSTATUS(exit_code_ping)
print ping_output
print exit_code

我观察到,如果具有给定 IP 的主机已关闭或无法访问,则代码可以正常工作。但是,如果主机启动,它会给我:

exit_code = os.WEXITSTATUS(exit_code_ping)
TypeError: an integer is required

由于我是 python 的初学者,所以我不知道问题出在哪里。

问题:我做错了什么,为什么这东西不起作用......最重要的是,我怎样才能让它起作用。

【问题讨论】:

    标签: python ping


    【解决方案1】:

    顺便说一句,您可以通过放入 try 块来修复您的 sn-p,当它成功时退出代码为 None:

    try:
        exit_code = os.WEXITSTATUS(exit_code_ping)
        print exit_code
    except Exception as er:
        print 'Error: ', er
    
    print ping_output
    

    更好的方法是使用子流程:

    import subprocess
    
    IP = '8.8.8.100'
    ping_command = "ping -c 5 -n -W 4 " + IP
    
    (output, error) = subprocess.Popen(ping_command,
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE,
                                       shell=True).communicate()
    
    print output, error
    

    【讨论】:

      【解决方案2】:

      使用subprocess. 模块,检查这个excellent piece of documentation about subprocess

      Popen.returncode 就是你要找的……

      How to get exit code when using Python subprocess communicate method?

      【讨论】:

        猜你喜欢
        • 2014-06-14
        • 2019-01-30
        • 2020-05-19
        • 1970-01-01
        • 2011-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多