首页 > 解决方案 > 后台python进程的命令行界面

问题描述

如何创建一个作为后台进程持续存在并且仅在输入特定命令时才执行命令的命令行界面?请注意以下基本上是伪代码:

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()

请注意这不是:

我熟悉clickargparsesubprocess等,据我所知,他们接受一个命令并阻塞直到完成。我特别寻找与后台进程交互的东西,以便只处理一次昂贵的启动(将对象加载到内存中)。我已经查看了 python守护程序服务包,但我不确定这些是否也是适合这项工作的工具。

我怎样才能做到这一点?我觉得好像我不知道用谷歌搜索什么才能得到我需要的答案......

标签: pythonshellserviceterminalbackground-process

解决方案


这只是您可以执行此操作的一种方法...(还有其他方法,这只是一个非常简单的方法)

您可以使用服务器作为长期运行的进程(然后您可以使用 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;

推荐阅读