1

关于 Python 专业化的 Google IT 自动化“使用 python 与操作系统交互”的第 1 周 Qwiklabs 评估:使用 Python 3rd 模块无法正常工作

在 ~/scripts 目录:network.py 代码

    #!usr/bin/env python3
import requests
import socket

def check_localhost():
    localhost = socket.gethostbyname('localhost')
    print(localhost)
    if localhost == '127.0.0.1':
        return True

    return False
def check_connectivity():
    request = requests.get("http://www.google.com")
    responses = request.status_code
    print(responses)
    if responses == 200:
        return True

    return False

通过使用此代码,我制作了“创建一个新的 Python 模块”

但 Qwiklab 告诉我,我无法正确编写代码。!!!

现在有什么问题?

4

4 回答 4

2

我在这里回复这篇文章是因为我注意到很多人在 Coursera 上学习这门课程“使用 Python 与操作系统交互”check_localhost在编写 Python 函数和check_connectivity. 请将这些功能复制到您的虚拟机并重试。为了 ping 网络并检查本地主机是否配置正确,我们将import requests模块和套接字模块。接下来,编写一个函数check_localhost,检查本地主机是否配置正确。我们通过gethostbyname在函数内调用来做到这一点。 localhost = socket.gethostbyname('localhost') 上述函数将主机名转换为 IPv4 地址格式。将参数 localhost 传递给函数gethostbyname。这个函数的结果应该是127.0.0.1. 编辑函数 check_localhost 以便在函数返回127.0.0.1时返回 true 。

import requests 
import socket 
#Function to check localhost
def check_localhost():
    localhost = socket.gethostbyname('localhost')
    if localhost == "127.0.0.1":
        return True
    else:
        return False

现在,我们将编写另一个名为check_connectivity. 这将检查计算机是否可以成功调用 Internet。请求是当您 ping 网站以获取信息时。Requests 库专为此任务而设计。您将为此使用请求模块,并通过传递 ahttp://www.google.com作为参数来调用 GET 方法。 request = requests.get("http://www.google.com") 这将返回网站的状态代码。此状态代码是一个整数值。现在,将结果分配给响应变量并检查该变量的 status_code 属性。它应该返回 200。编辑函数 check_connectivity 以便在函数返回 200 status_code 时返回 true。

#Function to check connectivity
def check_connectivity():
    request = requests.get("http://www.google.com")
    if request.status_code == 200:
        return True
    else:
        return False

完成文件编辑后,press Ctrl-o, Enter, and Ctrl-x to exit. 完成后,单击检查我的进度以验证目标

于 2021-11-08T06:00:19.323 回答
1

我使用您的相同代码来检查代码中的问题,但是您的代码成功通过了 qwiklabs 检查。

我认为有问题,您是否在本实验会话结束时重试并创建另一个会话只是为了检查这是否与他们的结束有问题。

在此处输入图像描述

于 2021-06-27T07:45:37.917 回答
0

即使您在帖子中遇到问题,此脚本也可以工作:

import requests
import socket
def check_localhost():
    localhost = socket.gethostbyname('localhost')
    return True # or return localhost == "127.0.0.1"
def check_connectivity():
    request = requests.get("http://www.google.com")
    return True #or return request==200

您的代码可能有什么问题?验证系统有问题,不接受:

-tab 而不是 4 个空格作为正确的标识

- 行与行之间的空格

于 2022-01-08T13:46:35.270 回答
0
#!usr/bin/env python3
import requests
import socket
def check_localhost():    
    localhost = socket.gethostbyname('localhost')
    print(localhost)
    if localhost == '127.0.0.1':
        return True
def check_connectivity():
    request = requests.get("http://www.google.com")
    responses = request.status_code()
    print(responses)
    if responses == '200':
        return True
于 2022-01-29T19:02:24.760 回答