模块urllib.request请求不会被抓到的

2024-09-30 01:32:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python3测试lynda的这个演示程序。我正在使用Pycharm作为我的IDE。我已经添加并安装了请求包,但是当我运行程序时,它运行得很干净,并显示一条消息“processfinished with exit code 0”,但不显示print语句的任何输出。我哪里出错了?你知道吗

import urllib.request # instead of urllib2 like in Python 2.7
import json


def printResults(data):
    # Use the json module to load the string data into a dictionary
    theJSON = json.loads(data)

    # now we can access the contents of the JSON like any other Python object
    if "title" in theJSON["metadata"]:
        print(theJSON["metadata"]["title"])

    # output the number of events, plus the magnitude and each event name
    count = theJSON["metadata"]["count"];
    print(str(count) + " events recorded")

    # for each event, print the place where it occurred
    for i in theJSON["features"]:
        print(i["properties"]["place"])

    # print the events that only have a magnitude greater than 4
    for i in theJSON["features"]:
        if i["properties"]["mag"] >= 4.0:
            print("%2.1f" % i["properties"]["mag"], i["properties"]["place"])

    # print only the events where at least 1 person reported feeling something
    print("Events that were felt:")
    for i in theJSON["features"]:
        feltReports = i["properties"]["felt"]
        if feltReports != None:
            if feltReports > 0:
                print("%2.1f" % i["properties"]["mag"], i["properties"]["place"], " reported " + str(feltReports) + " times")

    # Open the URL and read the data
    urlData = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson"
    webUrl = urllib.request.urlopen(urlData)
    print(webUrl.getcode())
    if webUrl.getcode() == 200:
        data = webUrl.read()
        data = data.decode("utf-8") # in Python 3.x we need to explicitly decode the response to a string
    # print out our customized results
        printResults(data)
    else:
        print("Received an error from server, cannot retrieve results " + str(webUrl.getcode()))

Tags: ofthetoinjsonfordataif
3条回答

安装完模块后,我不得不重新启动IDE。我刚刚意识到,并尝试现在与“运行作为管理员”。奇怪的是它似乎起作用了现在。但是不确定是否是临时错误,因为即使不重新启动,它也能够检测模块及其方法。你知道吗

您的评论是:必须重新启动IDE使我认为pycharm可能不会自动检测新安装的python包。这个答案似乎提供了一个解决方案。你知道吗

SO answer

不确定您是否故意遗漏了这一点,但是这个脚本实际上并没有执行导入和函数定义之外的任何代码。假设你没有故意漏掉它,你需要在你的文件末尾有以下内容。你知道吗

if __name__ == '__main__':
    data = "" # your data
    printResults(data)

__name__等于"__main__"的检查就是这样,您的代码只在文件显式运行时执行。要在访问文件时始终运行printResults(data)函数(例如,如果文件导入到另一个模块中),您可以在文件底部调用它,如下所示:

data = "" # your data
printResults(data)

相关问题 更多 >

    热门问题