Python Forum
exec + subprocess = UnboundLocalError
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
exec + subprocess = UnboundLocalError
#1
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
Reply
#2
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))
Reply
#3
indeed
I tested "eval" but at the wrong place Tongue
Thanks
Reply
#4
By the way, why dont you simply call the function?i
Launch = subprocess.Popen(['%s\exe' % Path, 'name=%s' % InputFile])
nilamo likes this post
Reply
#5
Thumbs Up

Simplier and clearer; still a lot of things to learn

Thanks
nilamo likes this post
Reply
#6
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.
ndc85430 likes this post
Reply
#7
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!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How does UnboundLocalError work? deanhystad 3 1,633 Feb-25-2022, 01:21 AM
Last Post: bowlofred
  UnboundLocalError: local variable 'wmi' referenced before assignment ilknurg 2 1,855 Feb-10-2022, 07:36 PM
Last Post: deanhystad
  How to avoid exec(), globals(), locals(), eval() paul18fr 10 4,902 Apr-21-2021, 05:53 PM
Last Post: snippsat
  exec in a function paul18fr 6 3,306 Apr-19-2021, 11:10 AM
Last Post: paul18fr
  UnboundLocalError: local variable 'figure_perso' referenced before assignment mederic39 2 2,227 Jun-11-2020, 12:45 PM
Last Post: Yoriz
  UnBoundLocalError Seaninho 3 2,618 May-31-2020, 07:22 AM
Last Post: azajali43
  exec() in class, NameError niski1996 6 3,870 Apr-20-2020, 07:14 PM
Last Post: niski1996
  Is this use of exec pythonic? psolar 1 1,796 Feb-07-2020, 12:23 PM
Last Post: buran
  UnboundLocalError: local variable referenced before assignment svr 1 3,258 Dec-27-2019, 09:08 AM
Last Post: perfringo
  problem using exec to save local variables dkarl 0 1,761 Dec-01-2019, 08:52 AM
Last Post: dkarl

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020