/usr/lib/python3/dist-packages/cement/ext/ext_alarm.py is in python3-cement 2.10.0-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 | """
The Alarm Extension provides easy access to setting an application alarm to
handle timing out operations. See the
`Python Signal Library <https://docs.python.org/3.5/library/signal.html>`_.
Requirements
------------
* No external dependencies.
* Only available on Unix/Linux
Configuration
-------------
This extension does not honor any application configuration settings.
Usage
-----
.. code-block:: python
import time
from cement.core.foundation import CementApp
from cement.core.exc import CaughtSignal
class MyApp(CementApp):
class Meta:
label = 'myapp'
exit_on_close = True
extensions = ['alarm']
with MyApp() as app:
try:
app.run()
app.alarm.set(3, "The operation timed out after 3 seconds!")
# do something that takes time to operate
time.sleep(5)
app.alarm.stop()
except CaughtSignal as e:
print(e.msg)
app.exit_code = 1
Looks like:
.. code-block:: console
$ python myapp.py
ERROR: The operation timed out after 3 seconds!
Caught signal 14
"""
import signal
from ..utils.misc import minimal_logger
LOG = minimal_logger(__name__)
def alarm_handler(app, signum, frame):
if signum == signal.SIGALRM:
app.log.error(app.alarm.msg)
class AlarmManager(object):
"""
Lets the developer easily set and stop an alarm. If the
alarm exceeds the given time it will raise ``signal.SIGALRM``.
"""
def __init__(self, *args, **kw):
super(AlarmManager, self).__init__(*args, **kw)
self.msg = None
def set(self, time, msg):
"""
Set the application alarm to ``time`` seconds. If the time is
exceeded ``signal.SIGALRM`` is raised.
:param time: The time in seconds to set the alarm to.
:param msg: The message to display if the alarm is triggered.
"""
LOG.debug('setting application alarm for %s seconds' % time)
self.msg = msg
signal.alarm(int(time))
def stop(self):
"""
Stop the application alarm.
"""
LOG.debug('stopping application alarm')
signal.alarm(0)
def load(app):
app.catch_signal(signal.SIGALRM)
app.extend('alarm', AlarmManager())
app.hook.register('signal', alarm_handler)
|