Do not show the output of a command in python when you use os.system ()

1

I'm trying to make a program that sends a ping to a certain number of IPs that the user enters through the terminal. for example:

python programa.py 10 20

I think it is appropriate to mention that the computer on which this tool is going to be has the windows operating system.

from sys import argv
from os import system
for ip in range(argv[1], argv[2] + 1):
    ping = system("ping 192.168.0.{}".format(ip))
    if ping == 1
        print("192.168.0.{} está apagada.".format(ip))
    else:
        print("192.168.0.{} está encendida.".format(ip))

The problem is that I do not want the output of the program to appear, because it looks something like this:

Haciendo ping a 127.0.0.1 con 32 bytes de datos:
Respuesta desde 127.0.0.1: bytes=32 tiempo<1m TTL=128
Respuesta desde 127.0.0.1: bytes=32 tiempo<1m TTL=128
Respuesta desde 127.0.0.1: bytes=32 tiempo<1m TTL=128
Respuesta desde 127.0.0.1: bytes=32 tiempo<1m TTL=128

Estadísticas de ping para 127.0.0.1:
    Paquetes: enviados = 4, recibidos = 4, perdidos = 0
    (0% perdidos),
Tiempos aproximados de ida y vuelta en milisegundos:
Mínimo = 0ms, Máximo = 0ms, Media = 0ms
127.0.0.1 está encendida.

I do not want the output of the program to appear so as not to distract the one who uses the tool (in this case a relative who asked me to show him how many people are connected to his network) so my question is

How can I prevent the STDOUT of a command from appearing in python?

Thank you very much to the one who takes the time to answer my question: 3

Note:

It does not necessarily have to be with os.system (), if it is possible with another line of code, there is no problem.

    
asked by binario_newbie 12.07.2018 в 01:44
source

2 answers

2

First, os.system in practice is considered as "deprecated" and should not be used in principle except to maintain backward compatibility. The natural substitute is the module subprocess , much more complete and that allows much more control and communication about the released process.

For Python 3.5 onwards subprocess.run is a good choice, there is only that redirect the standard output to os.devnull:

import subprocess
from sys import argv

for ip in range(argv[1], argv[2] + 1):
    out = subprocess.run("ping 192.168.0.{}".format(ip), stdout=subprocess.DEVNULL)

    if out.returncode == 1:
        print("192.168.0.{} está apagada.".format(ip))
    else:
        print("192.168.0.{} está encendida.".format(ip))

You can also redirect stderr if you wish.

    
answered by 12.07.2018 / 02:13
source
1

If you use the " system (COMANDO) function, the following might work:

Example

from os import system
os.system("ping TuDirecciónIP > nul")

When you add "& nt; nul" to the command, it will not generate any output.

Try that and tell me how it went.

    
answered by 12.07.2018 в 02:06