Home > Software engineering >  Win10 how can I know a python script is running?
Win10 how can I know a python script is running?

Time:10-13

I use os.system to call a python script with flask.

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 will execute for a long time, about 5 minutes.

If detect_for_all.py is executing, another request is sent to flask, the script detect_for_all.py will not be executed,some code like:

if detect_for_all.py is running:
    return
if detect_for_all.py is not running:
    os.system(cmd)

So how can I do this ckeck in my code?

CodePudding user response:

To search for a running process by arguments, you could try something like

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

You would use it as _search_proc_args(['python', 'detect_for_all.py']). It returns True if it finds a process with the given strings in the command line arguments.

CodePudding user response:

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

  • Related