python - 后台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()
请注意这不是:
- argparse 或 click 的典型示例,它运行(阻塞)python 进程,直到所有命令完成
- 每个命令的一系列一次性脚本;他们利用在后台进程中通过 startup() 实例化的内存中的对象
- 一个完全不同的外壳,比如 ipython;我想将它与标准 shell 集成,例如 bash。
我熟悉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;
推荐阅读
- tensorflow - 批处理结束后如何更改 Tensorflow 中的学习率?
- python - 在 python 包 install_requires 中指定“或”
- python - seaborn FacetGrid 垂直轴上的分层标签
- python - Python 到 C++ 通信失败
- python - 如何从 SymPy 中提取椭圆的中心坐标、高度、宽度和 phi 以绘制拟合椭圆?
- ignite - 如何为使用 Apache Ignite 的无状态服务挂载卷
- macos - 未加载库:在 Clion Editor 上执行 Valgrind 时 /usr/lib/libc++.1.dylib
- regex - HIVE - 从字符串列中获取所有匹配的文本
- c# - PDPSharp 图表位置和背景
- mysql - 如何使用 laravel 社交名流通过 facebook 登录?