Python signal processing signal module
Signal module Introduction
Recently, I have been reading Linux signal related content. signal can be used for inter-process communication and asynchronous processing. The Python Standard Library provides the signal package for signal processing. The signal module of Python in Unix systems is discussed here.
Signal Simple example
The official document provides the following example:
Import signal, OS # defines a Signal processing function that prints the received signal, and then raise IOErrordef handler (signum, frame): print 'signal handler called with signal ', signum raise IOError ("Couldn't open device! ") # Set the handler for processing the SIGALRM (termination), then set the timer, and trigger the SIGALRM signal in 5 seconds. signal (signal. SIGALRM, handler) signal. alarm (5) # This open () may hang indefinitelyfd = OS. open ('/dev/ttys0', OS. o_RDWR) signal. alarm (0) # Turn off the timer
In this example, a timer is set to trigger an IOError five seconds later to prevent file opening errors or other exceptions from waiting. If the file is opened normally within 5s, the timer is cleared.
Signal description
Basic Signal name
Import signalsignal. SIGABORTsignal. SIGHUP # connect and stop signal. SIGILL # Invalid command signal. SIGINT # connection interruption signal. SIGKILL # terminate the process (this signal cannot be captured or ignored) signal. SIGQUIT # exit signal from the terminal. SIGTERM # terminate signal. SIGALRM # timeout warning signal. SIGCONT # continue to execute the pause process and so on...
Common signal processing functions
Signal. signal (signalnum, handler)
Set the signal processing function
Signal. alarm (time)
Set the timer for sending SIGALRM signals
OS. kill
This does not belong to the signal module, but it can be used to send signals to a process.
Signal usage example
Example 1
# From project httpscreenshot-master, under directory , in source file httpscreenshot.py.def timeoutFn(func, args=(), kwargs={}, timeout_duration=1, default=None): import signal class TimeoutError(Exception): pass def handler(signum, frame): raise TimeoutError() # set the timeout handler signal.signal(signal.SIGALRM, handler) signal.alarm(timeout_duration) try: result = func(*args, **kwargs) except TimeoutError as exc: result = default finally: signal.alarm(0) signal.signal(signal.SIGALRM, signal.SIG_DFL) return result
In the preceding example, the default result is returned when the function execution times out. First, a time-out processing function is set, and a custom throw exception is thrown in the function. Set signal before executing the function. alarm: when the time limit is exceeded, it will trigger the exception SIGALRM, capture the default value of the exception settings, and then perform the cleanup operation to cancel the timer, and set the processing of SIGALRM to the default value.
Example 2
This example is from here. The requirement is to dynamically load the python import Module. that is to say, when the imported module code is updated, you want to update the referenced code immediately. Example:
# lib.pydef scrape_me_bro(): print "Scraping is fun"#scrape.pyimport timeimport signalimport libdef scrape(): # Assume we are hitting Streaming API # and doing something buzzwordy with it while True: lib.scrape_me_bro() time.sleep(2)def reload_libs(signum, frame): print "Received Signal: %s at frame: %s" % (signum, frame) print "Excuting a Lib Reload" reload(lib)# Register reload_libs to be called on restartsignal.signal(signal.SIGHUP, reload_libs)# Mainscrape()
When running scrape. in py, the program calls lib every two seconds. in py, the scrape_me_bro () method, if the lib. the method in py has changed, to run scrape. the process of py sends the SIGHUP signal, then it will reload lib. in this way, the modified scrape_me_bro () method will be executed cyclically.