[英]command line interface for background python process
How can I create a command line interface that persists as a background process and only executes commands when specific commands are entered?如何创建作为后台进程持续存在并且仅在输入特定命令时执行命令的命令行界面? Please note the following is basically pseudo code:请注意以下基本上是伪代码:
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()
Note what this is not:请注意这不是什么:
I am familiar with click , argparse , subprocess , etc., and as far as I can tell they accept a single command and block until completion.我熟悉click 、 argparse 、 subprocess等,据我所知,他们接受单个命令并阻塞直到完成。 I specifically seek something that interacts with a background process so that expensive startup (loading objects into memory) is handled only once.我特别寻找与后台进程交互的东西,以便只处理一次昂贵的启动(将对象加载到内存中)。 I have looked at both python daemon and service packages, but I'm unsure if these are the right tool for the job also.我已经查看了 python守护进程和服务包,但我不确定它们是否也适合这项工作。
How can I accomplish this?我怎样才能做到这一点? I feel as though I don't know what to google to get the answer I need...我觉得好像我不知道要谷歌什么才能得到我需要的答案......
this is just one way you might do this... (there are other ways as well, this is just a pretty simple method)这只是您可以这样做的一种方式...... (还有其他方式,这只是一个非常简单的方法)
you could use a server as your long running process (you would then turn it into a service using init systemV or upstart)您可以使用服务器作为您长时间运行的进程(然后您可以使用 init systemV 或 upstart 将其转换为服务)
hardworker.py勤奋者.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)
then your client could just make simple http requests against your "service"那么您的客户就可以针对您的“服务”发出简单的 http 请求
thin_client.sh瘦客户端.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.