Secondo lo Python os module documentation os.popen è stato deprecato da Python 2.6.
Penso che la soluzione per Python moderno sia utilizzare check_output() dal modulo subprocess.
Dal subprocess Python documentation:
subprocess.check_output (args, *, stdin = None, stderr = nessuno, shell = false, universal_newlines = False) comando di marcia con argomenti e restituisce la sua uscita come un byte stringa.
Se il codice di ritorno era diverso da zero, genera un errore CalledProcessError. L'oggetto CalledProcessError avrà il codice di ritorno nell'attributo returncode e qualsiasi output nell'attributo output.
Se si esegue attraverso il seguente codice in Python 2.7 (o successiva):
import subprocess
try:
print subprocess.check_output(["ping", "-n", "2", "-w", "2", "1.1.1.1"])
except subprocess.CalledProcessError, e:
print "Ping stdout output:\n", e.output
Si dovrebbe vedere un output simile a questa:
Ping stdout output:
Pinging 1.1.1.1 with 32 bytes of data:
Request timed out.
Request timed out.
Ping statistics for 1.1.1.1:
Packets: Sent = 2, Received = 0, Lost = 2 (100% loss),
L'e.output la stringa può essere analizzata per soddisfare le esigenze dell'OP.
Se si desidera che il codice di ritorno o altri attributi, sono in CalledProccessError come si può vedere facendo un passo attraverso con PDB
(Pdb)!dir(e)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
'__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__',
'__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__',
'__unicode__', '__weakref__', 'args', 'cmd', 'message', 'output', 'returncode']
//, Vuoi includere un collegamento alla documentazione per questo, https://docs.python.org/2/library/subprocess.html#subprocess.CalledProcessError, in questa domanda? –