[英]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.