The script
#!/usr/bin/env python3
import subprocess
import time
import sys
low = int(sys.argv[1]); high = int(sys.argv[2]); command = sys.argv[3:]; proc = command[0]
def get_temps():
data = subprocess.check_output("sensors").decode("utf-8").splitlines()
return sum([[float(l.split(":")[1].split()[0].replace("+", "").replace("°C", "")) \
for l in data if l.startswith(mark)]for mark in ["temp1", "Core"]], [])
def manage_start():
try:
pid = subprocess.check_output(["pgrep", proc]).decode("utf-8").strip()
subprocess.Popen(["killall", "-s", "CONT", proc])
except subprocess.CalledProcessError:
subprocess.Popen(["/bin/bash", "-c", (" ").join(command)])
run = False
while True:
time.sleep(1)
if run == False:
if all([n < low for n in get_temps()]):
manage_start(); run = True
elif run == True:
if not all([n < high for n in get_temps()]):
subprocess.Popen(["killall", "-s", "STOP", proc]); run = False
How to use
- Copy the script into an empty file, save it as
temp_run.py
Run it, best before the process runs (the script will start the process), with (subsequently) the low_temp
, the high_temp
, the process_name
and possible arguments, as arguments. I tested it for example with:
python3 /path/to/temp_run.py 60 80 gedit /path/to/file.txt
(using another plain text editor to change the numbers)
How I tested it
Since I do not have the variety in real temperature, in the script, I replaced the function get_temps()
, by a function, reading numbers from a text file.
Thus "feeding" the script with virtual temperatures, it did the job without an error: pausing above "high" when running, resuming below "low" when paused.
How it works
When the script starts
- it checks if all temperatures are below the lowest threshold.
- If so, it either starts the process, or resumes it if it runs already, and sets the variable:
run = True
- As a result, the next test then is if all temps are below the highest threshold, if not, the process is paused, the script sets:
run = False
, making the next test if all temps are below the lowest and so on...
How to kill it
The script can be killed by:
kill "$(pgrep -f temp_run.py)"
command -a 1
.