I am using subprocess.check_output from pythons subprocess module to execute a ping command. Here is how I am doing it:
output = subprocess.check_output(["ping","-c 2 -W 2","1.1.1.1")
It is raising a CalledProcessError and says the output is one of the arguments of the function. Can anyone help me how to read that output. I would like to read the output into a string and parse it. So say for example if the ping returns
100% packet loss
I need to capture that. If there is any other better way..please suggest. Thanks.
I ran into the same problem and found that the documentation has example for this type of scenario (where we write STDERR TO STDOUT and always exit successfully with return code 0) without causing/catching an exception.
Now, you can use standard string function
find
to check the output stringoutput
.In the list of arguments, each entry must be on its own. Using
should fix your problem.
According to the Python os module documentation os.popen has been deprecated since Python 2.6.
I think the solution for modern Python is to use check_output() from the subprocess module.
From the subprocess Python documentation:
If you run through the following code in Python 2.7 (or later):
You should see an output that looks something like this:
The e.output string can be parsed to suit the OPs needs.
If you want the returncode or other attributes, they are in CalledProccessError as can be seen by stepping through with pdb
If you want to get stdout and stderr back (including extracting it from the CalledProcessError in the event that one occurs), use the following:
This is Python 2 and 3 compatible.
If your command is a string rather than an array, prefix this with:
Thanx @krd, I am using your error catch process, but had to update the print and except statements. I am using Python 2.7.6 on Linux Mint 17.2.
Also, it was unclear where the output string was coming from. My update:
I see an output like this: