Python Signal Processing Signal module

Source: Internet
Author: User
Tags signal handler terminates

Signal Module Introduction

Recently looking at Linux signal related content, signal can be used for interprocess communication and asynchronous processing. The Python standard library provides signal packages that can be used to handle signal correlation. The signal module for Python in UNIX systems is discussed here.

Signal Simple Example

An example of this is available in the official documentation:

Import signal, os# defines a signal handler 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!") # SIGALRM (termination) Set the processing of the handler, then set the timer, 5 seconds after the trigger SIGALRM signal signal.signal (signal. SIGALRM, Handler) Signal.alarm (5) # This open () could hang INDEFINITELYFD = Os.open ('/dev/ttys0 ', OS. O_RDWR) signal.alarm (0)          # off Timer

The example implements the function of setting a timer to trigger ioerror after 5 seconds in order to prevent an error in opening a file, or if another exception has been in a waiting state. If the file is open normally within 5s, the timer is cleared.

Signal description

The basic signal name

Import signalsignal. Sigabortsignal.sighup  # Connection hangs off signal. Sigill  # illegal directive signal. SIGINT  # Connection Interrupt signal. SIGKILL # Terminates the process (this signal cannot be captured or ignored) signal. Sigquit # terminal exits signal. SIGTERM # terminates signal. SIGALRM  # Timeout warning signal. Sigcont  # Resume The pause process, etc...

Commonly used signal processing functions

Signal.signal (Signalnum, handler)

function to set signal processing

Signal.alarm (Time)

Setting timers for sending SIGALRM signals

Os.kill

This is not part of the signal module, but it can be used to send a signal to a process

Signal Use Example

Example 1

# from Project Httpscreenshot-master, under directory, in source file Httpscreenshot.py.def Timeoutfn (func, args= (), Kwar gs={}, 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

The above example implements the ability to set the function execution timeout to return the default result. First, a timeout handler is set to throw out the defined throw exception in the function. The Signal.alarm is set before the function is executed, the exception is triggered when the time is exceeded SIGALRM, then the default value is caught, and the last cleanup is canceled, and the processing of SIGALRM is set to default.

Example 2

This example comes from here. The requirement is to dynamically load the Python-imported module, which means that when the imported module code is updated, you want to update the referenced code immediately. Examples are as follows:

# Lib.pydef Scrape_me_bro ():        print "Scraping is fun" #scrape. Pyimport timeimport signalimport libdef Scrape ():        # Assume we is 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 "E Xcuting a Lib Reload "        Reload (Lib) # Register Reload_libs to is called on restartsignal.signal (signal. SIGHUP, Reload_libs) # Mainscrape ()

When running scrape.py, the program calls the Scrape_me_bro () method in lib.py every two seconds, and if the method in the lib.py changes and sends a scrape.py signal to the process running SIGHUP, it reloads lib.py , which then loops through the modified Scrape_me_bro () method.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.