简体   繁体   中英

How do I import a variable from another Python script if the variable is only set within a define function?

So I have two scripts, a main one and a secondary one. The main script is just mainly GUI code but I wanted one of the buttons to set a variable and then call in the second script. The second script should then import the variable and continue on with it, however this isn't the case.

I tried presetting the variable outside the GUI code and theoretically it should change once the button is pressed but the second code simply imports the original variable.

from second import recognition
repeater = True
task = "placeholder"

def resume():
    while repeater:
        try:
            task = "hello"
            print(task)
            recognition()
def recognition():
    import first
    task = first.task
    print(task)

I thought that both print functions would print "hello", however the second print function prints "placeholder" instead.

EDIT: I've tried putting

global task

under

def resume():
while repeater:

and

try:

but to no avail.

You need to let python know that you want to modify the global task - otherwise python will create a new local variable with name task inside resume

Adding a global task declaration inside the function should do the job

from second import recognition
repeater = True
task = "placeholder"

def resume():
    global task
    while repeater:
        try:
            task = "hello"
            print(task)
            recognition()

What you want is the global keyword inside your function. This causes it to use the external variable.

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