我正在尝试使用Python 3从lynda测试这个演示程序。我正在使用Pycharm作为我的IDE。我已经添加并安装了请求包,但当我运行该程序时,它运行得很干净,并显示一条消息"Process finished 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()))
不确定您是否故意忽略了这一点,但该脚本实际上并没有执行导入和函数定义之外的任何代码。假设你不是故意遗漏的,那么你需要在文件的末尾写下以下内容。
if __name__ == '__main__':
data = "" # your data
printResults(data)
对__name__
等于"__main__"
的检查只是为了让您的代码只有在显式运行文件时才执行。要在文件被访问时始终运行printResults(data)
函数(比如,如果它被导入到另一个模块中),你可以在文件底部这样调用它:
data = "" # your data
printResults(data)
您的评论是:必须重新启动IDE,这让我认为pycharm可能无法自动检测新安装的python包。这个SO的答案似乎提供了一个解决方案。
SO应答