0

I have a headless piece of hardware which can be remotely updated.

The hardware does little more than run a python script at boot. I'm trying to improve the robustness of this update system.

If I were to update the hardware with a bugged python script (such as a mis-spelt print or return(it happens!) or missing a colon) then the python interpreter would refuse to run it as it parses the whole script first.

On this 'parse' it would return back a syntax error. How can I catch this and perform a different action?

Harvey
  • 1,320
  • 3
  • 13
  • 33
  • 2
    you could do `python foo.py 2>&1 | grep "SyntaxError:"` (since return code won't help you there: it's 1 on invalid syntax), rely on `grep` return code, and rely on `PIPESTATUS` for script return code – Jean-François Fabre Jan 30 '17 at 16:40
  • 2
    I would recommend to use a python linter (pep8) so that you're always sure that you don't have syntax errors – edi9999 Jan 30 '17 at 16:41
  • you could also try to compile your code (http://stackoverflow.com/questions/471191/why-compile-python-code) – Jean-François Fabre Jan 30 '17 at 16:42
  • One idea is to write a script that wraps execution of your boot script (with `execfile` or similar), and from there you can catch `SyntaxError`s. Seems a little hacky to me though. – 0x5453 Jan 30 '17 at 16:43
  • 2
    Write tests for your code – wim Jan 30 '17 at 16:43
  • 1
    Start with fixing your deployment process, and don't waste your time engineering around its deficiencies. – chepner Jan 30 '17 at 16:43

1 Answers1

0

You can make a wrapper script to catch the SyntaxError using execfile like:

try:
   execfile('/path/to/script.py')
except SyntaxError:
   # do the other thing
Grisha Levit
  • 8,194
  • 2
  • 38
  • 53