Skip to content

Instantly share code, notes, and snippets.

@DiegoQueiroz
Last active May 17, 2018 16:50
Show Gist options
  • Save DiegoQueiroz/a8b14690f5d3bcb39eb68a87b71dd4b3 to your computer and use it in GitHub Desktop.
Save DiegoQueiroz/a8b14690f5d3bcb39eb68a87b71dd4b3 to your computer and use it in GitHub Desktop.
Run a process and prepare it to terminate when it becomes orphan
# -*- coding: utf-8 -*-
# RunMe.Py
# 2018 - Diego Queiroz
#
# Usage:
# Linux : python /path/to/RunMe.py /path/to/your/your_script.sh
# Windows: C:\path\to\python.exe C:\path\to\RunMe.py C:\path\to\your_script.bat
#
import atexit
import subprocess
import os
import sys
import psutil
# It has only one parameter, that is the file to be called
# Be warned: it does NOT support complex scripts
# Each line of the script will be called until it find one that spawn a process
filename = ' '.join(sys.argv[1:])
def parent_running():
return psutil.pid_exists(os.getppid())
with open(filename, 'r') as f:
for line in f:
# for each line of the script
try:
# spawn a new process and keep track of the PID
process = subprocess.Popen(line[:-1], cwd=os.path.dirname(sys.argv[1]))
# log process name
print(os.linesep + os.path.dirname(filename)+ '>' + line + os.linesep)
sys.stdout.flush()
# mark the PID to terminate when this process terminate
atexit.register(process.terminate)
# wait 1 second for the process to run
# this first check exists because sometimes
# the process terminate very fast
try:
exitcode = process.wait(1)
except subprocess.TimeoutExpired:
exitcode = None
# loop while process is still running
while exitcode is None:
# check if parent is running
# if not, break loop
if not parent_running():
exitcode = 255 # inform error
break
# wait 1 second for the process to finish
# then check again if the parent is running
try:
exitcode = process.wait(1)
except subprocess.TimeoutExpired:
exitcode = None
# if the process terminated, break loop
# if you want the script to check other lines
# you may try to change this to "continue" instead of "break"
if exitcode != 0:
break
except FileNotFoundError:
# ignore if the process can't run (comments, etc)
pass
# propagate last exitcode
sys.exit(exitcode)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment