如何在python中更新全局变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17307474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 07:50:02  来源:igfitidea点击:

how to update global variable in python

pythonlistfunctionglobal

提问by Vaibhav Aggarwal

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.

在 python 中,我有一个函数可以返回网站上最新链接(到文件夹)的列表。我还有另一个功能可以从这些文件夹下载最新文件。我计划每天运行这个脚本。我有一个全局列表,其中包含下载功能每次为最新文件夹运行时访问的文件夹链接。我想每五天更新一次全局列表,并在接下来的 5 天内保持静态我运行代码直到它再次更新。

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?

所以我希望更新功能每 5 天运行一次(我知道怎么做)并且下载功能每天运行一次。那么如何将 update() 返回的列表作为全局列表保持静态,直到它再次更新?

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?

我重新启动了我的代码,但现在列表没有从星期一开始的 link3。如何在接下来的 5 天内将 link3 保留在列表中,直到我再次更新列表?

Thanks

谢谢

采纳答案by Ashwini Chaudhary

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

使用global语句。但是global如果您在原地修改它们,则不需要可变对象。

You can use modules like pickleto 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.

您可以使用诸如pickle将列表存储在文件中之类的模块。您可以在需要使用列表时加载列表,并在进行修改后将其存储回来。

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 cPicklemodule.

为了获得更好的性能,您还可以使用cPickle模块。

More examples

更多例子

回答by Stephan

As long as it is declared in the main program and not within the scope of the function you should be fine to manipulate your listvariable from there (your comment) just fine. If you want initialize it as global to from within the scope of a method you can use the globalkeyword to broaden the scope to the whole program

只要它是在主程序中声明的,而不是在函数的范围内,您就可以list从那里(您的评论)操作您的变量就好了。如果要将其初始化为全局范围内的方法,则可以使用global关键字将范围扩大到整个程序

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

def update():
  list.append("link25")
  return list

will append link25 to the global list as you wanted

将根据需要将 link25 附加到全局列表

If you want your list to be persistent between runs, you can save it to a file and load it from that file each time or save it to a database and load it from a database if you need it to work on multiple machines

如果您希望您的列表在运行之间保持不变,您可以将它保存到一个文件并每次从该文件加载它,或者将它保存到一个数据库并从数据库加载它(如果您需要它在多台机器上工作)

you can write the items in your list to a file by doing this

您可以通过执行此操作将列表中的项目写入文件

for item in thelist:
    thefile.write("%s\n" % item)

source

来源

回答by rocker_raj

Normal declaration of the variable will make it local.
Use global keyword to make it render as global.

变量的正常声明将使其成为局部变量。
使用 global 关键字使其呈现为全局。

Just write the list to a file and access it read it from there later.

只需将列表写入文件并访问它,然后从那里读取它。

If you don't want to self run the code you can use cron-job to do it for you.

如果您不想自行运行代码,可以使用 cron-job 为您完成。

def read_file(filename):
    f = open(filename).read().split()
    lis = []
    for i in f:
            lis.append(i)
    return lis 

def write_file(filename,lis):
        f = open(filename,"w")
        for i in lis:
                f.write(str(i)+'\n')