简体   繁体   English

Python中的全局变量可在文件之间共享变量

[英]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: 我有一个获取命令行参数的Python脚本,然后将其存储为脚本中的全局变量:

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". Python中的global表示“在该模块内”。 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 . 甚至更好的是,将其作为func的参数传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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