简体   繁体   中英

Global variables in Python to share variable across files

I have a Python script that gets a command line argument, and then it is stored as a global variable within the script:

global chain
chain = sys.argv[1]

The script then imports a couple of other files, each containing another function. I am trying to carry the value of this variable to the other functions as well, by doing the following:

def func():
    global chain
    #do stuff

which is contained in another file than the original script.

When I run the script, I get

NameError: global name 'chain' is not defined

What am I missing?

global in Python means "within that module". It does not share names across modules.

If you want to access a variable defined in one module from another, simply import it:

from my_module import chain

or, even better, pass it as an argument to func .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM