1

I am currently writing a python program that contains a section where it pings a target computer to see and it if responds, changes a variable, but when I execute the code the ping command writes to the console (which I don't want).

I have checked the ping commands parameters to see if there is something to make it silent but was unable to find anything. Is there something I can do to stop the command to echoing to the console?

My code below:

if platform.system().lower() == "windows":
        parameter = "-n"
    else:
        parameter = "-c"

    exitCode = subprocess.call(f"ping {parameter} 1 {activeConnections[ip][0]}")
    if (exitCode == 0):
        activeConnections[ip][3] = "T"

activeConnections is a dictionary and if the ping is successful, a value is changed from "F" to "T".

Red
  • 26,798
  • 7
  • 36
  • 58
Darcy Power
  • 195
  • 12

1 Answers1

1

You can use the devnull attribute of the built-in os module:

from os import devnull
from subprocess import STDOUT

# Your code

if platform.system().lower() == "windows":
    parameter = "-n"
else:
    parameter = "-c"

with open(devnull) as DEVNULL:
    exitCode = subprocess.call(f"ping {parameter} 1 {activeConnections[ip][0]}", stdout=DEVNULL, stderr=STDOUT))

if (exitCode == 0):
    activeConnections[ip][3] = "T"
Red
  • 26,798
  • 7
  • 36
  • 58