Python Forum

Full Version: exec + subprocess = UnboundLocalError
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all

In the following code extract, "Launch.wait()" generates an error only if it is inserted in a function (it works in the program core); "Launch" variable does not exist outside the function so it remains a local variable.

I would like to understand what I'm missing (

Thanks

def RunExe(Path, InputFile):
    exec("Launch = subprocess.Popen(['%s\exe', 'name=%s'])" %(Path, InputFile))
    Launch.wait()
    del Launch
Error:
UnboundLocalError: local variable 'Launch' referenced before assignment
See the note in the documentation of the exec() function: modification of the default locals() should not be attempted.

You could replace this with
Launch = eval("subprocess.Popen(['%s\exe', 'name=%s'])" %(Path, InputFile))
indeed
I tested "eval" but at the wrong place Tongue
Thanks
By the way, why dont you simply call the function?i
Launch = subprocess.Popen(['%s\exe' % Path, 'name=%s' % InputFile])
Thumbs Up

Simplier and clearer; still a lot of things to learn

Thanks
As a general rule, if you're using eval(), you're doing something wrong. It's dangerous, and there's close to zero reasons to ever need it.
nilamo Wrote:if you're using eval(), you're doing something wrong. It's dangerous,
Executing Python code is already very dangerous. There is little difference with eval. Even storing Python scripts on your hard drive is dangerous. Watch out for wrong file permissions!