Python Forum
exec + subprocess = UnboundLocalError - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: exec + subprocess = UnboundLocalError (/thread-32300.html)



exec + subprocess = UnboundLocalError - paul18fr - Feb-02-2021

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



RE: exec + subprocess = UnboundLocalError - Gribouillis - Feb-02-2021

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))



RE: exec + subprocess = UnboundLocalError - paul18fr - Feb-02-2021

indeed
I tested "eval" but at the wrong place Tongue
Thanks


RE: exec + subprocess = UnboundLocalError - Gribouillis - Feb-02-2021

By the way, why dont you simply call the function?i
Launch = subprocess.Popen(['%s\exe' % Path, 'name=%s' % InputFile])



RE: exec + subprocess = UnboundLocalError - paul18fr - Feb-02-2021

Thumbs Up

Simplier and clearer; still a lot of things to learn

Thanks


RE: exec + subprocess = UnboundLocalError - nilamo - Feb-03-2021

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.


RE: exec + subprocess = UnboundLocalError - Gribouillis - Feb-04-2021

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!