robert robert - 6 months ago 7x
Python Question

Efficient way to ask python to stop (controlled) from bash (/tmp/stop?)

What is the most efficient way (in terms of polling overhead) to request a Python program to stop (in a controlled way) from a Bash script. On python side I want a function (which executes as fast as possible) which returns true when a stop is requested or false if not. If true we save our work, release resources and exit.

For some simple tools I implemented the following:

  • In bash I do a
    touch /tmp/stop

  • My Python program polls on a frequent basis
    does exist. If it exists if quits in a controlled way.

  • My bash script waits (loop - sleep - ps) until the related process is stopped.

This solution works, but polling for this file is most likely not the most efficient way.

Are there other options with less overhead (in terms of Python polling time)?


The UNIX signal mechanism would be an excellent choice. You don't need any temporary files, and the polling overhead is essentially zero.

You may shutdown the following python program gracefully like so: kill -USR1 $pid.

import signal
import time
import sys

please_stop = False
def setup_signal():
    def handler(x,y):
        global please_stop
        please_stop = True
    signal.signal(signal.SIGUSR1, handler)

def main_task():
    for i in range(10):
        print "Working hard on iteration #%d"%i
        if please_stop:
            print "Stopping now"