在python中禁止OS命令提示符弹出

时间:2018-02-09 10:02:31

标签: python ping

import subprocess, platform

def ping(host):
    args = "ping -n 1 " + host
    return subprocess.call(args) == 0

打印(平( “www.google.com”))

我正在使用此代码来ping网站以测试它是向上还是向下,这完全有效,但是它会导致短暂出现的命令提示窗口,这对我正在处理的工作来说并不理想,所以我的问题是; 如何让这个窗口出现在ping请求上(需要基于窗口的解决方案)

1 个答案:

答案 0 :(得分:-1)

要使用ping来了解地址是否正在响应,请使用其返回值,该值为0表示成功。如果返回值不为0,则subprocess.check_call将引发错误。要抑制输出,请重定向stdout和stderr。使用Python 3,您可以使用subprocess.DEVNULL而不是在块中打开空文件。

import os
import subprocess

with open(os.devnull, 'w') as DEVNULL:
    try:
        subprocess.check_call(
            ['ping', '-c', '3', '10.10.0.100'],
            stdout=DEVNULL,  # suppress output
            stderr=DEVNULL
        )
        is_up = True
    except subprocess.CalledProcessError:
        is_up = False

价:Get output of system ping without printing to the console

相关问题