[英]command line interface for background python process
如何创建作为后台进程持续存在并且仅在输入特定命令时执行命令的命令行界面? 请注意以下基本上是伪代码:
def startup():
# costly startup that loads objects into memory once in a background process
def tear_down()
# shut down; generally not needed, as main is acting like a service
def main():
startup()
# pseudo code that checks shell input for a match; after execution releases back to shell
while True:
usr_in = get_current_bash_command()
if usr_in == "option a":
# blocking action that release control back to shell when complete
if usr_in == "option b":
# something else with handling like option a
if usr_in == "quit":
# shuts down background process; will not be used frequently
tear_down()
break
print("service has been shut down. Bye!")
if __name__ == "__main__":
# run non-blocking in background, only executing code if usr_in matches commands:
main()
请注意这不是什么:
我熟悉click 、 argparse 、 subprocess等,据我所知,他们接受单个命令并阻塞直到完成。 我特别寻找与后台进程交互的东西,以便只处理一次昂贵的启动(将对象加载到内存中)。 我已经查看了 python守护进程和服务包,但我不确定它们是否也适合这项工作。
我怎样才能做到这一点? 我觉得好像我不知道要谷歌什么才能得到我需要的答案......
这只是您可以这样做的一种方式...... (还有其他方式,这只是一个非常简单的方法)
您可以使用服务器作为您长时间运行的进程(然后您可以使用 init systemV 或 upstart 将其转换为服务)
勤奋者.py
import flask
app = flask.Flask("__main__")
@app.route("/command1")
def do_something():
time.sleep(20)
return json.dumps({"result":"OK"})
@app.route("/command2")
def do_something_else():
time.sleep(26)
return json.dumps({"result":"OK","reason":"Updated"})
if __name__ == "__main__":
app.run(port=5000)
那么您的客户就可以针对您的“服务”发出简单的 http 请求
瘦客户端.sh
if [[ $1 == "command1" ]]; then
curl http://localhost:5000/command1
else if [[ $1 == "command2" ]]; then
curl http://localhost:5000/command2
fi;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.