根据Python os module documentation os.popen自Python 2.6以来已被弃用。
我认为现代Python的解决方案是使用来自子流程模块的check_output()。
从subprocess Python documentation:
subprocess.check_output(参数,*,标准输入=无,标准错误=无,壳=假,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的需要。
如果你想返回码或其他属性,它们在CalledProccessError如可以通过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']
//,你会在这个问题中包含一个指向这个文档的链接,https://docs.python.org/2/library/subprocess.html#subprocess.CalledProcessError? –