how to update global variable in python

为君一笑 提交于 2019-12-04 06:37:36

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.

More examples

Normal declaration of the variable will make it local.
Use global keyword to make it render as 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.

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')
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 list variable 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 global keyword to broaden the scope to the whole program

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

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

will append link25 to the global list as you wanted

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!