从时间模块获得一个列表输出



我有一个代码,每2秒运行一次。此代码每两秒钟打印一次坐标信息。我想把这些坐标集合成一个列表,但是我做不到。我该怎么做呢?

代码:

import time
import requests
import schedule

def executeSomething():

r = requests.get('https://get.geojs.io/')
ip_request = requests.get("https://get.geojs.io/v1/ip.json")
ippAdd = ip_request.json()["ip"]
url = 'https://get.geojs.io/v1/ip/geo/' + ippAdd + '.json'
geo_request = requests.get(url)
geo_data = geo_request.json()

co=[]
co.append([float(geo_data["latitude"]),float(geo_data["longitude"])])
print(co)

schedule.every(2).seconds.do(executeSomething)#This code run every 10 seconds
#schedule.every().hour.do(executeSomething())

while 1:
schedule.run_pending()
time.sleep(1)

输出:

[[39.9208, 32.8375]]
[[39.7856, 32.2174]]

但是我想要这样的输出:

[[39.9208, 32.8375], [39.7856, 32.2174]]

编辑:我还有一个问题。当changeprint(co)toreturn co然后将这个函数导入到另一段代码中并尝试获得">

import dynamic
d = dynamic.executeSomething()
print(d)

我做错了什么?

每次循环运行时,通过在函数中包含co=[]来重置列表,因为它每次都调用该函数。

co=[]移到函数的上方和外部。

import time
import requests
import schedule
co=[]
def executeSomething():

r = requests.get('https://get.geojs.io/')
ip_request = requests.get("https://get.geojs.io/v1/ip.json")
ippAdd = ip_request.json()["ip"]
url = 'https://get.geojs.io/v1/ip/geo/' + ippAdd + '.json'
geo_request = requests.get(url)
geo_data = geo_request.json()
co.append([float(geo_data["latitude"]),float(geo_data["longitude"])])
print(co)

schedule.every(2).seconds.do(executeSomething)#This code run every 10 seconds
#schedule.every().hour.do(executeSomething())

while 1:
schedule.run_pending()
time.sleep(1)

最新更新