我os.system過去常常用 Flask 呼叫 python 腳本。
from flask import Flask
from flask import request
import os
import json
import datetime
app = Flask(__name__)
#url test-> http://192.168.1.186:8081/detectForCar?source=D:/test.mp4
@app.route('/detectForCar', methods=['GET','POST'])
def detectForCar():
source = request.args.get("source")
ip = request.remote_addr
if source:
if os.path.exists(source):
try:
# if detect_for_all.py is not running, run os.system(cmd)
cmd = 'python detect_for_all.py --source %s' %source
os.system(cmd)
str_response = {'message': 'success'}
json_response = json.dumps(str_response,ensure_ascii=False)
return json_response
except Exception as ex:
str_response = {'message': 'error'}
json_response = json.dumps(str_response,ensure_ascii=False)
return json_response
if __name__ == '__main__':
app.run(host='192.168.1.186' ,port=8081)
detect_for_all.py 會執行很長時間,大約5分鐘。
如果detect_for_all.py正在執行,則向flask發送另一個請求,腳本detect_for_all.py將不會執行,一些代碼如下:
if detect_for_all.py is running:
return
if detect_for_all.py is not running:
os.system(cmd)
那么我怎樣才能在我的代碼中做這個檢查呢?
uj5u.com熱心網友回復:
要按引數搜索正在運行的行程,您可以嘗試類似
import psutil
def _search_proc_args(keys):
for proc in psutil.process_iter(['cmdline']):
try:
if (args := proc.info['cmdline']) is not None:
if all(s in args for s in keys):
return True
# catch NoSuchProcess for procs that disappear inside loop
except (psutil.AccessDenied, psutil.NoSuchProcess):
pass
return False
您可以將其用作_search_proc_args(['python', 'detect_for_all.py']). True如果在命令列引數中找到具有給定字串的行程,則回傳。
uj5u.com熱心網友回復:
import subprocess
# for linux
cmd = "ps -ef|grep python"
res = subprocess.check_output(cmd, shell=True)
# all running process related to python will be in res
# if you want to know is there a "detect_for_all.py"
if "detect_for_all.py" in str(res):
# do your jobs
pass
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/316761.html
