【发布时间】:2019-09-05 15:08:52
【问题描述】:
我有以下代码返回设备的 ping 状态:
def ping_check(hostname):
response = os.system("ping -c 3 " + hostname)
if response == 0:
pingstatus = "Online"
else:
pingstatus = "Offline"
return pingstatus
效果很好并且按预期工作。但是,我想将 ping 输出保存到一个变量中,但我不知道该怎么做。
现在的输出如下所示:
>>> hostname = "google.com"
>>> op = os.system("ping -c 3 " + hostname)
PING google.com (172.217.7.206) 56(84) bytes of data.
64 bytes from iad30s10-in-f14.1e100.net (172.217.7.206): icmp_seq=1 ttl=48 time=1.56 ms
64 bytes from iad30s10-in-f14.1e100.net (172.217.7.206): icmp_seq=2 ttl=48 time=1.57 ms
64 bytes from iad30s10-in-f14.1e100.net (172.217.7.206): icmp_seq=3 ttl=48 time=1.52 ms
--- google.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2012ms
rtt min/avg/max/mdev = 1.526/1.552/1.572/0.049 ms
>>>
我想将 ping 的实际输出保存到一个变量中,这样我就可以将它放入一些东西中以供以后使用。非常感谢任何帮助。
【问题讨论】:
-
看看
subprocess模块 -
您无法保存来自
os.system()的输出,因为您的程序实际上从未收到它 - 它直接进入您的终端。正如 dcg 所说,使用subprocess。