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 to avoid exec(), globals(), locals(), eval() paul18fr 10 1,083 Apr-21-2021, 05:53 PM
Last Post: snippsat
  exec in a function paul18fr 6 790 Apr-19-2021, 11:10 AM
Last Post: paul18fr
  UnboundLocalError: local variable 'figure_perso' referenced before assignment mederic39 2 748 Jun-11-2020, 12:45 PM
Last Post: Yoriz
  UnBoundLocalError Seaninho 3 843 May-31-2020, 07:22 AM
Last Post: azajali43
  exec() in class, NameError niski1996 6 1,070 Apr-20-2020, 07:14 PM
Last Post: niski1996
  Is this use of exec pythonic? psolar 1 682 Feb-07-2020, 12:23 PM
Last Post: buran
  UnboundLocalError: local variable referenced before assignment svr 1 1,337 Dec-27-2019, 09:08 AM
Last Post: perfringo
  problem using exec to save local variables dkarl 0 672 Dec-01-2019, 08:52 AM
Last Post: dkarl
  UnboundLocalError: local variable ' ' referenced before assignment d3fi 10 2,411 Sep-03-2019, 07:22 PM
Last Post: buran
  'Exception Has occured: UnBoundLocalError' caston 1 971 Jun-12-2019, 02:33 PM
Last Post: perfringo

Forum Jump:

User Panel Messages

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