简体   繁体   English

如何退出Flask应用程序中调用的python脚本?

[英]How to exit a python script called in a Flask app?

I have a flask app where I am reusing a function in a python script (poll_servers.py). 我有一个烧瓶应用程序,我在python脚本(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: 这是我在python脚本中的代码:

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: 在我的app.py中我有:

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: 我在sys.exit(1)上收到错误:

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. 如果我自己运行poll_servers.py, sys.exit(1)工作正常。

Then just don't do anything or flip the order of your if statement: 然后只是不做任何事情或翻转你的if语句的顺序:

import os
import sys

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

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

        pass

else:

    pass
    # do something

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM