python检测到网络时调用函数

1 投票
2 回答
660 浏览
提问于 2025-04-17 17:08

我知道有一些方法可以检查现在是否有网络,但我找不到可以在网络连接上来时调用某个函数的方法。有没有类似的东西呢?

我在使用Ubuntu系统,不需要支持其他操作系统。最好是用Python 3。我可以安装外部库来实现这个功能。

2 个回答

-2

之前在这里已经回答过了。

import urllib2

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

一种简单的方法就是使用轮询,可以用一个叫做 ping模块

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客户端 的东西,阅读一些 规范 可能会有帮助。

你也可以使用Python的 线程接口 来进行后台轮询。

撰写回答