Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if ping was successful using subprocess in python

I execute the ping command in python by opening a cmd window with the ping command using python's subprocess module.
For example:

import subprocess
p = subprocess.Popen('ping 127.0.0.1')

Afterwards I check if the output contains "Reply from 'ip':", to see if the ping was successful.
This works in all cases where the cmd is in english.
What can I do to check if a ping was successful on any cmd language?

like image 626
yuval Avatar asked Mar 02 '16 14:03

yuval


People also ask

How do I run a ping command in Python?

By hand: 1) open cmd 2) ping 8.8. 8.8 -n 1 3) echo %ERRORLEVEL% . Code: Modify the last line of the Python code to return system_call(command) . With proper connectivity you will get 0 (zero).

What is shell true in subprocess Python?

Setting the shell argument to a true value causes subprocess to spawn an intermediate shell process, and tell it to run the command. In other words, using an intermediate shell means that variables, glob patterns, and other special shell features in the command string are processed before the command is run.

What does subprocess Check_output do in Python?

The subprocess. check_output() is used to get the output of the calling program in python. It has 5 arguments; args, stdin, stderr, shell, universal_newlines. The args argument holds the commands that are to be passed as a string.


1 Answers

Using python on Linux, I would use check_output()

subprocess.check_output(["ping", "-c", "1", "127.0.0.1"])

this will return true if the ping is successful

like image 191
elfosardo Avatar answered Nov 05 '22 11:11

elfosardo