python所有变量更新,如何更新python中的全局变量

In python, i have a function that returns a list of the latest links(to folders) on a website. I also have another function that downloads the latest files from those folders. I plan to run this script everyday. I have a global list with the folder links that the download function accesses everytime it runs for the latest folders. I want to update that global list every five days and keep it static for the next 5 days i run the code until it updates again.

Its sort of like this:

list = ["link1", "link2",...]

def update():

#code to update list

return list

def download(list):

#code to download from links

So I want the update function to run every 5 days(I know how to do that) and the download function to run everyday. So how can i keep the list returned from update() static as the global list until it is updated again?

EDIT:

Let me try to clarify:

I run this on a monday:

list = ["link1", "link2"]

def update():

#code to update list

return list #--> list = ["link1", "link2", "link3"]

def download(list):

#code to download from links

this worked fine, list was updated and used in download().

I run this on a Tuesday:

list = ["link1", "link2"]

#update() won't run today, only runs every 5 days

def update():

#code to update list

return list #--> list = ["link1", "link2", "link3"]

def download(list):

#code to download from links

I restarted my code, but now list doesnt have link3 from monday. How do i keep link3 in the list for the next 5 days until i update list again?

Thanks

解决方案

Use global statement. But there's no need of global for mutable objects, if you're modifying them in-place.

You can use modules like pickle to store your list in a file. You can load the list when you want to use it and store it back after doing your modifications.

lis = ["link1", "link2",...]

def update():

global lis

#do something

return lis

Pickle example:

import pickle

def update():

lis = pickle.load( open( "lis.pkl", "rb" ) ) # Load the list

#do something with lis #modify it

pickle.dump( lis, open( "lis.pkl", "wb" ) ) #save it again

For better performance you can also use the cPickle module.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值