Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python每5分钟保存一次数据_Python_Json_Debian_Urllib2 - Fatal编程技术网

使用python每5分钟保存一次数据

使用python每5分钟保存一次数据,python,json,debian,urllib2,Python,Json,Debian,Urllib2,当时我正在做一个python myprogra.py&,让这个程序完成它的工作: import urllib2 import threading import json url = 'https://something.com' a = [] def refresh(): # refresh in 5 minutes threading.Timer(300.0, refresh).start() # open url try: data =

当时我正在做一个
python myprogra.py&
,让这个程序完成它的工作:

import urllib2
import threading
import json

url = 'https://something.com'
a = []

def refresh():

    # refresh in 5 minutes
    threading.Timer(300.0, refresh).start()

    # open url
    try:
        data = urllib2.urlopen(url).read(1000)
    except:
        return 0

    # decode json
    q = data.decode('utf-8')
    q = json.loads(q)

    # store in a
    a.append(q['ticker'])

    if len(a) > 288:
        a.pop()

    truc = json.dumps(a)

    f = open('ticker.json', 'w')
    f.write(truc)
    f.close()


refresh()
我有两个问题:

  • 既然我没有在函数开始时编写
    global a
    ,它是如何工作的

  • 我应该用cron来做这类事情而不是我正在做的事情吗?(我正在使用debian服务器)


以您的方式访问变量
a
没有问题,因为您从未在
刷新
功能中为其赋值。它的访问方式与
url
变量,甚至是
json
导入的访问方式非常相同。如果要分配给
a
(而不是在其上调用
append
之类的方法),则将创建一个局部变量来隐藏全局a。
global
关键字避免为赋值创建局部变量

是否使用休眠或cron程序取决于您,但这里有一些事情需要记住:

  • 您的程序在变量
    a
    中跨请求保持状态。如果要使用cron并多次调用程序,则需要将此状态存储在其他位置
  • 如果您的程序崩溃(例如返回无效数据,json解码因异常而失败),cron将再次启动它,因此它最终会恢复。这可能是也可能不是所希望的
  • 当通过cron运行时,以牺牲更多计算为代价降低了系统的内存占用(Python解释器每五分钟初始化一次)
+1。注意:
Timer()
也会在5分钟内启动,无论函数是否成功。