0

I have a flask app where I am reusing a function in a python script (poll_servers.py). I can import the function and run it but I want to put a check in place that exits the function if it's running.

Here is my code in the python script:

import os
import sys

# check if lock file exists, exit
if os.path.exists('static/poll.lock'):
    sys.exit(1)

if not os.path.exists('static/poll.lock'):
    with open('static/poll.lock', 'w'): pass

In my app.py I have:

from poll_servers import poll

@app.route('/poll_servers', methods=['GET'])
def poll_servers():

    response = json.dumps({'status':'OK'})

    poll()

    return response

I get an error on the sys.exit(1) in poll_servers.py:

File "app.py", line 109, in poll_servers
  poll()
File ".../poll_servers.py", line 262, in poll
  sys.exit(1)
File ".../venv/lib/python2.7/site.py", line 403, in __call__
  raise SystemExit(code)
SystemExit: None

Any ideas? If I run the poll_servers.py on its own the sys.exit(1) works fine.

MoreScratch
  • 2,933
  • 6
  • 34
  • 65
  • Which error is thrown? – Joe May 30 '19 at 08:10
  • Works fine for me if I change `static/poll.lock` to `/tmp/poll.lock`. – Joe May 30 '19 at 08:14
  • I added the error. Still throws an exception when moving the lock file to the `tmp` directory as suggested. – MoreScratch May 30 '19 at 13:41
  • https://stackoverflow.com/questions/52427999/python-flask-app-not-exiting-with-sys-exit – Joe May 30 '19 at 14:10
  • The file can stay in `static`, this won't change anything. I just used a different path. – Joe May 30 '19 at 14:12
  • 3
    Possible duplicate of [Python Flask app not exiting with sys exit](https://stackoverflow.com/questions/52427999/python-flask-app-not-exiting-with-sys-exit) – Joe May 30 '19 at 14:12
  • I don't want Flask to exit, I just need the imported function `poll` to stop executing if a lock file is found. – MoreScratch May 30 '19 at 14:13

1 Answers1

0

Then just don't do anything or flip the order of your if statement:

import os
import sys

if not os.path.exists('static/poll.lock'):

    with open('static/poll.lock', 'w'): 

        pass

else:

    pass
    # do something
Joe
  • 6,758
  • 2
  • 26
  • 47