【问题标题】:Get output as a list from time module从时间模块获取输出作为列表
【发布时间】:2021-01-19 07:41:22
【问题描述】:

我有一个每 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]]

编辑: 我还有一个问题。当把print(co)改成return co并把这个函数导入另一个代码并尝试获取“co”列表时,我无法获取。

import dynamic

d = dynamic.executeSomething()
print(d)

我做错了什么?

【问题讨论】:

  • 修正你的身份。
  • 我修正了标识。
  • 您在每次运行时将 co 重置为函数内的空列表。

标签: python list time request


【解决方案1】:

每次循环运行时,您都在重置列表,方法是在您的函数中包含 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)

【讨论】:

  • 非常感谢@GazSte
猜你喜欢
  • 2022-12-31
  • 1970-01-01
  • 2016-08-03
  • 1970-01-01
  • 2021-07-08
  • 2020-06-17
  • 2020-12-16
  • 2014-09-22
相关资源
最近更新 更多