Python, run exec() on a string 'return' to exit a function or thread

784 views Asked by At

I would like to run exec() on 'return' in my function, so that my function returns and stops, here is my code:

def Function():#recieves time consuming function to do
    #checks if main thread should be closed, if so returns:
    return 'return "it worked"'
    #otherwise returns 'Null' so main thread keeps going

def MainThread():
    #Wants to do some function, so 
    exec(Function())
    return "didnt work"

when I run MainThread(), it says:

SyntaxError: 'return' outside function

And I am not sure what is wrong there, I have simplified it and found that running exec('return') will also not work in a function.

Why I want to do this: I have a thread that controls instruments, and before each command that it sends to the instruments I want it to check if it should abort, since controlling the instruments can be time consuming, and there are safety hazards. I don't want to copy-paste an if statement many times through my code, so thought of wrapping each command to an instrument with a check. It seems quite messy, if there are other approaches I would love to hear. My current solution is:

def Function(stuff):#recieves time consuming function to do
#does things to stuff
return

def check(thing,skip):
    if skip==true:
        return
    else:
        Function(thing)
        return

def MainThread():
    skip = False #will be true or false if need to skip
    #Wants to do some function, so 
    check("the thing to do",skip)

If its necessary to abort the thread, it actually just skips through and does nothing at each function. At the end of the thread is aborts, but I didn't like simply keeping the thread there doing nothing and hoped for a better idea :)

1

There are 1 answers

0
DYZ On

exec() does not execute the code in the context of the function in which it is called. The "return "it worked"" does not become a part of Function(), it is executed on it's own.