欢迎访问宙启技术站
智能推送

用Python编写的判断判断函数可用性的代码示例

发布时间:2023-12-11 10:11:04

下面是一个使用Python编写的判断函数可用性的代码示例:

import requests

def check_function_availability(url):
    try:
        response = requests.get(url)
        if response.status_code == 200:
            return True
        else:
            return False
    except requests.exceptions.RequestException:
        return False

# 使用例子
if __name__ == '__main__':
    # 判断Google主页是否可用
    if check_function_availability("https://www.google.com"):
        print("Google is available")
    else:
        print("Google is not available")

    # 判断不存在的网址是否可用
    if check_function_availability("https://www.thiswebsitedoesnotexist123456789.com"):
        print("This website is available")
    else:
        print("This website is not available")

这个示例代码中的 check_function_availability 函数用来判断指定的URL是否可用。它使用 requests 库发送一个GET请求到指定URL,并检查返回的状态码是否为200。如果状态码为200,则说明网站可以访问,函数返回 True;否则返回 False

在使用例子中,我们首先判断Google主页是否可用。如果可用,打印 "Google is available";如果不可用,打印 "Google is not available"。

接下来,我们判断一个不存在的网址是否可用。由于该网址并不存在,所以访问会失败。函数会返回 False,打印 "This website is not available"。

通过这个代码示例,我们可以方便地判断函数可用性,并进行相应的处理。你可以根据需要修改 check_function_availability 函数来适应不同的场景。