0

I have a massive Python script that needs to be restarted automatically when it breaks. When I try a standard approach by wrapping the script into a function and then calling it via while True, I get this error:

SyntaxError: unqualified exec is not allowed in function 'wrappedFunc' because it contains a nested function with free variables

As I understand, this is due to the fact that my main script has sub functions. Can I still do it somehow via Python or should this be done in Windows via a batch file?

Aacini
  • 65,180
  • 12
  • 72
  • 108
sprogissd
  • 2,755
  • 5
  • 24
  • 45
  • 3
    It sounds like you should eliminate the `exec`s. – user2357112 Jul 02 '18 at 18:09
  • Can you show us your code? – blhsing Jul 02 '18 at 18:09
  • Are you in a position to upgrade to Python 3? Apparently if you do, [this error won't occur.](https://stackoverflow.com/a/41368813/953482) – Kevin Jul 02 '18 at 18:13
  • @Kevin Unfortunately, not. – sprogissd Jul 02 '18 at 18:14
  • @Kevin: But the reason the error won't occur is that Python 3 no longer tries to support assigning to function locals inside `exec`. Such assignments are now basically undefined behavior and mostly don't work (there are some caveats), so there would just be other errors. – user2357112 Jul 02 '18 at 18:26
  • Ok, you caught me: I was just trying to increase Python 3 adoption rates without actually addressing the underlying problem ;-) – Kevin Jul 02 '18 at 18:30
  • Exec should be avoided anyway. What exactly are you doing with it? – Daniel Roseman Jul 02 '18 at 18:30
  • @Daniel Roseman I use it to grab the content of my SQL files and save it as strings with the names the same as files names `exec (query_name + " = data")`. – sprogissd Jul 02 '18 at 20:07
  • As others have said, you should use a dict instead. – Daniel Roseman Jul 02 '18 at 21:35
  • @Daniel Roseman Do I understand it right that if I take this route, I will create not variables but dictionary entries? So in my example instead of calling variable `query_name`, I would have to call `my_dict[query_name]`? – sprogissd Jul 02 '18 at 21:45
  • Yes. That is the correct approach for this kind of thing. – Daniel Roseman Jul 02 '18 at 21:56

2 Answers2

0

The error is related to using the exec keyword inside a function that has subfunctions. Python needs you to explicitly determine which scope the exec will use to run in this case.

nosklo
  • 217,122
  • 57
  • 293
  • 297
0

exec command: execfile('file.py'). Insecure and kind of hack hacky. Avoid wherever possible. Spawn a shell process: os.system('python file.py'). Use when desperate.

PS: i haven't tried it to invoke/run same file

Anurag Jain
  • 439
  • 5
  • 12