根据Python 操作系统模块文档 http://docs.python.org/library/os.html#os.popen自 Python 2.6 起,os.popen 已被弃用。
我认为现代 Python 的解决方案是使用 subprocess 模块中的 check_output() 。
来自子进程 Python 文档 http://docs.python.org/library/subprocess.html:
subprocess.check_output(args,*,stdin =无,stderr =无,shell = False,universal_newlines = False)
使用参数运行命令并将其输出作为字节字符串返回。
如果返回码非零,则会引发 CalledProcessError。 CalledProcessError 对象将在 returncode 属性中包含返回代码,并在 output 属性中包含任何输出。
如果您在 Python 2.7(或更高版本)中运行以下代码:
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
您应该看到如下所示的输出:
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),
可以解析 e.output 字符串以满足 OP 的需要。
如果您想要返回代码或其他属性,它们位于 CalledProcessError 中,可以通过 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']