【问题标题】:python call function when internet is found找到互联网时的python调用函数
【发布时间】:2013-02-26 05:00:15
【问题描述】:

我知道有办法检查当前是否有互联网,但无论如何我都找不到在找到互联网时实际调用函数。有这样的东西吗?

我使用的是 Ubuntu,不需要支持任何其他操作系统。 最好是python 3。 我可以安装外部库来执行此操作。

【问题讨论】:

  • 您可以处理 NetworkManager 的 dbus 信号之一:stackoverflow.com/questions/4401851/…
  • pythonic 的方式是 try: 它,并处理你不能在 except: 块中的情况。
  • 找到网络时需要调用这个函数,我不在乎程序第一次运行时是否有网络,只是每次在程序运行时连接互联网,我也是不想在每个小步舞曲左右都检查互联网,因为这可能会错过快速切换到不同模式等内容,并且它不适用于我想要制作的程序。
  • 搅拌机建议似乎很有用的dbus,看起来应该有一种方法可以使用它,但我还没有想出任何东西。稍后我会对此进行更多研究。

标签: python


【解决方案1】:

穷人的方式是使用ping module 进行轮询

import ping, time

def found():
    print("FOUND INTERNET! :)")
def lost():
    print("LOST INTERNET! :(")

def wait_and_notify_connection(found, lost, already_found=False):
    while True:
        # Ping Google DNS Server (99.999% Uptime)
        if ping.do_one('8.8.8.8', timeout=2, psize=64) is not None:                
            if not already_found:
                found()
                already_found = True
        else:
            if already_found:
                lost()
                already_found = False
        time.sleep(1)

wait_and_notify_connection(found, lost)

或者子进程调用

import subprocess, time

def found():
    print("FOUND INTERNET! :)")
def lost():
    print("LOST INTERNET! :(")

def ping(target):
    return True if subprocess.call(['ping', '-c 1', target]) == 0 else False

def wait_and_notify_connection(found, lost, already_found=False):
    while True:
        # Ping Google DNS Server (99.999% Uptime)
        # and check return code
        if ping('8.8.8.8'):
            if not already_found:
                found()
                already_found = True
        else:
            if already_found:
                lost()
                already_found = False
        time.sleep(1)

wait_and_notify_connection(found, lost)

但正如@Blender 所提到的,D-Bus 通知可以更好地工作。像NetworkManager D-Bus Python client 和阅读some specs 这样的东西可能会有所帮助。

您也可以使用 Python 的 threading interface 进行后台轮询

【讨论】:

    【解决方案2】:

    以前回答过here.

    import urllib2
    
    def internet_on(url):
        try:
            response=urllib2.urlopen(url,timeout=1)
            return True
        except urllib2.URLError as err: pass
        return False
    

    【讨论】:

    • 这个函数为我返回False
    • 我编辑了我的帖子,我不应该盲目复制帖子,我很确定帖子使用的是旧的 google ip。地址。现在传入您要测试的任何 URL。
    • 不是我正在寻找的答案,因为我需要类似事件侦听器的东西,但是,对于 googlers,python 3 的方法是使用“from urllib.request import urlopen”代替“导入 urllib2”,并使用 urlopen() 而不是 urllib2.urlopen()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-14
    相关资源
    最近更新 更多