【问题标题】:Pinging the internet to check for connectivityping 互联网以检查连接性
【发布时间】:2018-08-15 16:36:28
【问题描述】:

在尝试找到检查有效 Internet 连接的最简单方法时,我发现了这一点:

os.system("ping google.com")

但是,我似乎无法使用它。不管我用它做什么,它似乎永远在一个循环中运行。

输出:

PING google.com (172.217.6.206) 56(84) 字节数据。 64 字节 lga25s54-in-f206.1e100.net (172.217.6.206):icmp_seq=1 ttl=55 时间=61.8 ms 来自 lga25s54-in-f206.1e100.net (172.217.6.206) 的 64 个字节: icmp_seq=2 ttl=55 time=61.7 ms 64 字节 lga25s54-in-f206.1e100.net (172.217.6.206):icmp_seq=3 ttl=55 time=61.9 ms 来自 lga25s54-in-f206.1e100.net 的 64 个字节

--- google.com ping 统计 --- 7 个数据包传输,7 个数据包接收,0% 数据包丢失,时间 6009ms rtt min/avg/max/mdev = 61.666/61.784/61.910/0.203 毫秒

所以我的问题是我怎样才能用某种逻辑来使用这条线?换句话说,我如何在这方面(或类似的东西)使用它:

if os.system("ping google.com") == (some condition):
    some logic

【问题讨论】:

  • 它永远循环运行的原因是,当您从 cli 中调用 ping 实用程序时,它就是这样工作的
  • 你不能使用 ping 因为它永远运行,而且 os.system 也不返回程序打印的内容
  • :(我的希望和梦想...

标签: python-3.x


【解决方案1】:

如果您只想检查互联网连接,那么我想这应该可以满足您的目的

import requests

def check_internet_connection(url='http://www.google.com/', timeout=1):
    try:
        response = requests.get(url, timeout=timeout)
        return True
    except requests.ConnectionError:

        return False

print(check_internet_connection())

编辑:

这可以使用 popen

检查连接是否存在
import os
a = os.popen('ping -c 1 google.com').read()
if a:
    print('Internet connection working')
else:
    print('Internet connection Error')

【讨论】:

  • 谢谢,但我已经有其他方法可以检查互联网连接,但这不是我想要的。
  • 我已经更新了答案,但是你需要使用 popen 因为 os.system 不会保存输出
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-15
  • 2017-03-16
  • 2014-02-08
  • 2012-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多