-1
import subprocess, platform

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

print(ping("www.google.com"))

I am using this code in order to ping a website to test whether it is up or down, which works perfectly, however it results in a command prompt window briefly appearing which is not ideal for what I am working on, so my question is; How can I supress this window from appearing on pings requests (windows based solution needed)

Csarg
  • 353
  • 1
  • 4
  • 15

1 Answers1

-1

To use ping to know whether an address is responding, use its return value, which is 0 for success. subprocess.check_call will raise and error if the return value is not 0. To suppress output, redirect stdout and stderr. With Python 3 you can use subprocess.DEVNULL rather than opening the null file in a block.

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

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

Roushan
  • 4,074
  • 3
  • 21
  • 38