Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a Python job is running using PHP

I've got a python script thats called twice a day via a CRON job to trigger an alarm that runs in a loop, and is terminated by pressing a physical button and calling a destroy function when that button is pressed.

So far so good.

Now, I'd like to check via PHP if that script is running - so before the button is pressed but after it's called via CRON.

How can I do this?

Based on this question - I've tried the following:

exec("jobs", $pids);
if(!empty($pids)) {
    print_r($pids);
}

But it doesn't seem to be returning any value. Calling jobs from the terminal works as expected and lists the job as running when invoking the script directly using python3 alarm.py &.

Using exec("ps -A | grep -i $processName | grep -v grep", $pids); I feel won't work since the process ID can change and can not be known until the script is running.

like image 476
Michał Avatar asked Dec 04 '25 08:12

Michał


1 Answers

Use pgrep for this:

pgrep -f 'python scriptname.py ...'

-f can be used specify the full command line of the python process to avoid collision with multiple python processes running in parallel.

like image 180
hek2mgl Avatar answered Dec 05 '25 22:12

hek2mgl