Python signal.SIGINT Examples

The following are 30 code examples for showing how to use signal.SIGINT(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module signal , or try the search function .

Example 1
Project: jawfish   Author: war-and-code   File: test_break.py    License: MIT License 6 votes vote down vote up
def testInterruptCaught(self):
        default_handler = signal.getsignal(signal.SIGINT)

        result = unittest.TestResult()
        unittest.installHandler()
        unittest.registerResult(result)

        self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler)

        def test(result):
            pid = os.getpid()
            os.kill(pid, signal.SIGINT)
            result.breakCaught = True
            self.assertTrue(result.shouldStop)

        try:
            test(result)
        except KeyboardInterrupt:
            self.fail("KeyboardInterrupt not handled")
        self.assertTrue(result.breakCaught) 
Example 2
Project: jawfish   Author: war-and-code   File: test_break.py    License: MIT License 6 votes vote down vote up
def testSecondInterrupt(self):
        result = unittest.TestResult()
        unittest.installHandler()
        unittest.registerResult(result)

        def test(result):
            pid = os.getpid()
            os.kill(pid, signal.SIGINT)
            result.breakCaught = True
            self.assertTrue(result.shouldStop)
            os.kill(pid, signal.SIGINT)
            self.fail("Second KeyboardInterrupt not raised")

        try:
            test(result)
        except KeyboardInterrupt:
            pass
        else:
            self.fail("Second KeyboardInterrupt not raised")
        self.assertTrue(result.breakCaught) 
Example 3
Project: jawfish   Author: war-and-code   File: test_break.py    License: MIT License 6 votes vote down vote up
def testHandlerReplacedButCalled(self):
        # If our handler has been replaced (is no longer installed) but is
        # called by the *new* handler, then it isn't safe to delay the
        # SIGINT and we should immediately delegate to the default handler
        unittest.installHandler()

        handler = signal.getsignal(signal.SIGINT)
        def new_handler(frame, signum):
            handler(frame, signum)
        signal.signal(signal.SIGINT, new_handler)

        try:
            pid = os.getpid()
            os.kill(pid, signal.SIGINT)
        except KeyboardInterrupt:
            pass
        else:
            self.fail("replaced but delegated handler doesn't raise interrupt") 
Example 4
Project: jawfish   Author: war-and-code   File: test_break.py    License: MIT License 6 votes vote down vote up
def testRemoveResult(self):
        result = unittest.TestResult()
        unittest.registerResult(result)

        unittest.installHandler()
        self.assertTrue(unittest.removeResult(result))

        # Should this raise an error instead?
        self.assertFalse(unittest.removeResult(unittest.TestResult()))

        try:
            pid = os.getpid()
            os.kill(pid, signal.SIGINT)
        except KeyboardInterrupt:
            pass

        self.assertFalse(result.shouldStop) 
Example 5
Project: mqtt2sql   Author: curzon01   File: mqtt2sql.py    License: GNU General Public License v3.0 6 votes vote down vote up
def exitus(self, status=0, message="end"):
        """
        Called when the program should be exit

        @param status:
            the exit status program returns to callert
        @param message:
            the message logged before exit
        """
        # pylint: disable=global-statement
        global SCRIPTNAME
        global SCRIPTPID
        global VER
        # pylint: enable=global-statement
        if message is not None:
            log(1, message)
        log(0, '{}[{}] v{} end'.format(SCRIPTNAME, SCRIPTPID, VER))
        if status in (signal.SIGINT, signal.SIGTERM):
            status = 0
        sys.exit(status) 
Example 6
Project: tomodachi   Author: kalaspuff   File: test_dummy_service.py    License: MIT License 6 votes vote down vote up
def test_dummy_service(monkeypatch: Any, capsys: Any, loop: Any) -> None:
    services, future = start_service('tests/services/dummy_service.py', monkeypatch)

    assert services is not None
    assert len(services) == 1
    instance = services.get('test_dummy')
    assert instance is not None
    assert instance.start is True
    assert instance.started is True
    assert instance.stop is False

    assert tomodachi.get_instance() == instance
    assert tomodachi.get_service() == instance
    assert tomodachi.get_service('test_dummy') == instance
    assert tomodachi.get_service('test_dummy_nonexistant') is None

    async def _async_kill():
        os.kill(os.getpid(), signal.SIGINT)

    loop.create_task(_async_kill())
    loop.run_until_complete(future)

    assert instance.stop is True 
Example 7
Project: tomodachi   Author: kalaspuff   File: test_aws_sns_sqs_transport.py    License: MIT License 6 votes vote down vote up
def test_publish_invalid_credentials(monkeypatch: Any, capsys: Any, loop: Any) -> None:
    services, future = start_service('tests/services/dummy_service.py', monkeypatch)

    instance = services.get('test_dummy')

    with pytest.raises(AWSSNSSQSException):
        loop.run_until_complete(AWSSNSSQSTransport.publish(instance, 'data', 'test-topic', wait=True))

    async def _async_kill():
        os.kill(os.getpid(), signal.SIGINT)

    loop.create_task(_async_kill())
    loop.run_until_complete(future)

    if not future.done():
        future.set_result(None)

    out, err = capsys.readouterr()
    assert 'The security token included in the request is invalid' in err
    assert out == '' 
Example 8
Project: tomodachi   Author: kalaspuff   File: test_amqp_transport.py    License: MIT License 6 votes vote down vote up
def test_publish_invalid_credentials(monkeypatch: Any, capsys: Any, loop: Any) -> None:
    services, future = start_service('tests/services/dummy_service.py', monkeypatch)

    instance = services.get('test_dummy')

    with pytest.raises(AmqpException):
        loop.run_until_complete(AmqpTransport.publish(instance, 'data', 'test.topic', wait=True))

    async def _async_kill():
        os.kill(os.getpid(), signal.SIGINT)

    loop.create_task(_async_kill())
    loop.run_until_complete(future)

    out, err = capsys.readouterr()
    assert 'Unable to connect [amqp] to 127.0.0.1:54321' in err
    assert out == '' 
Example 9
Project: tomodachi   Author: kalaspuff   File: test_relative_imports.py    License: MIT License 6 votes vote down vote up
def test_relative_import_service(monkeypatch: Any, capsys: Any, loop: Any) -> None:
    services, future = start_service('tests/services/relative_service.py', monkeypatch)

    assert services is not None
    assert len(services) == 1
    instance = services.get('test_relative')
    assert instance is not None
    assert instance.start is True
    assert instance.started is True
    assert instance.stop is False

    async def _async_kill():
        os.kill(os.getpid(), signal.SIGINT)

    loop.create_task(_async_kill())
    loop.run_until_complete(future)

    assert instance.stop is True 
Example 10
Project: tomodachi   Author: kalaspuff   File: amqp_service_with_credentials_without_protocol.py    License: MIT License 6 votes vote down vote up
def _started_service(self) -> None:
        async def publish(data: Any, routing_key: str) -> None:
            await amqp_publish(self, data, routing_key=routing_key, wait=False)

        async def _async() -> None:
            async def sleep_and_kill() -> None:
                await asyncio.sleep(10.0)
                if not self.closer.done():
                    self.closer.set_result(None)

            task = asyncio.ensure_future(sleep_and_kill())
            await self.closer
            if not task.done():
                task.cancel()
            os.kill(os.getpid(), signal.SIGINT)
        asyncio.ensure_future(_async())

        self.data_uuid = str(uuid.uuid4())
        await publish(self.data_uuid, 'test.raw.topic') 
Example 11
def _started_service(self) -> None:
        async def publish(data: Any, topic: str) -> None:
            await aws_sns_sqs_publish(self, data, topic=topic, wait=False, message_protocol=CustomProtocol)

        async def _async() -> None:
            async def sleep_and_kill() -> None:
                await asyncio.sleep(10.0)
                if not self.closer.done():
                    self.closer.set_result(None)

            task = asyncio.ensure_future(sleep_and_kill())
            await self.closer
            if not task.done():
                task.cancel()
            os.kill(os.getpid(), signal.SIGINT)
        asyncio.ensure_future(_async())

        self.data_uuid = str(uuid.uuid4())
        for _ in range(30):
            if self.test_topic_data_received:
                break
            await publish(self.data_uuid, 'test-custom-topic')
            await asyncio.sleep(0.1) 
Example 12
Project: tomodachi   Author: kalaspuff   File: aws_sns_sqs_service_with_credentials.py    License: MIT License 6 votes vote down vote up
def _started_service(self) -> None:
        async def publish(data: Any, topic: str) -> None:
            await aws_sns_sqs_publish(self, data, topic=topic, wait=False)

        async def _async() -> None:
            async def sleep_and_kill() -> None:
                await asyncio.sleep(10.0)
                if not self.closer.done():
                    self.closer.set_result(None)

            task = asyncio.ensure_future(sleep_and_kill())
            await self.closer
            if not task.done():
                task.cancel()
            os.kill(os.getpid(), signal.SIGINT)
        asyncio.ensure_future(_async())

        self.data_uuid = str(uuid.uuid4())
        await publish(self.data_uuid, 'test-topic-unique')
        for _ in range(30):
            if self.test_topic_data_received:
                break
            await publish(self.data_uuid, 'test-topic')
            await asyncio.sleep(0.1) 
Example 13
Project: tomodachi   Author: kalaspuff   File: amqp_service_with_credentials_with_custom_protocol.py    License: MIT License 6 votes vote down vote up
def _started_service(self) -> None:
        async def publish(data: Any, routing_key: str) -> None:
            await amqp_publish(self, data, routing_key=routing_key, wait=False, message_protocol=CustomProtocol)

        async def _async() -> None:
            async def sleep_and_kill() -> None:
                await asyncio.sleep(10.0)
                if not self.closer.done():
                    self.closer.set_result(None)

            task = asyncio.ensure_future(sleep_and_kill())
            await self.closer
            if not task.done():
                task.cancel()
            os.kill(os.getpid(), signal.SIGINT)
        asyncio.ensure_future(_async())

        self.data_uuid = str(uuid.uuid4())
        await publish(self.data_uuid, 'test.custom.topic') 
Example 14
def _started_service(self) -> None:
        async def publish(data: Any, topic: str) -> None:
            await aws_sns_sqs_publish(self, data, topic=topic, wait=False)

        async def _async() -> None:
            async def sleep_and_kill() -> None:
                await asyncio.sleep(10.0)
                if not self.closer.done():
                    self.closer.set_result(None)

            task = asyncio.ensure_future(sleep_and_kill())
            await self.closer
            if not task.done():
                task.cancel()
            os.kill(os.getpid(), signal.SIGINT)
        asyncio.ensure_future(_async())

        self.data_uuid = str(uuid.uuid4())
        for _ in range(30):
            if self.test_topic_data_received:
                break
            await publish(self.data_uuid, 'test-raw-topic')
            await asyncio.sleep(0.1) 
Example 15
Project: tomodachi   Author: kalaspuff   File: amqp_service_with_credentials.py    License: MIT License 6 votes vote down vote up
def _started_service(self) -> None:
        async def publish(data: Any, routing_key: str) -> None:
            await amqp_publish(self, data, routing_key=routing_key, wait=True)

        async def _async() -> None:
            async def sleep_and_kill() -> None:
                await asyncio.sleep(10.0)
                if not self.closer.done():
                    self.closer.set_result(None)

            task = asyncio.ensure_future(sleep_and_kill())
            await self.closer
            if not task.done():
                task.cancel()
            os.kill(os.getpid(), signal.SIGINT)
        asyncio.ensure_future(_async())

        self.data_uuid = str(uuid.uuid4())
        await publish(self.data_uuid, 'test.topic') 
Example 16
Project: tomodachi   Author: kalaspuff   File: test_non_packaged_imported_service.py    License: MIT License 6 votes vote down vote up
def test_non_named_sub_service(monkeypatch: Any, capsys: Any, loop: Any) -> None:
    services, future = start_service('tests/services/test-copy/test.py', monkeypatch)

    assert services is not None
    assert len(services) == 1
    instance = services.get('test_dummy')
    assert instance is not None
    assert instance.start is True
    assert instance.started is True
    assert instance.stop is False

    async def _async_kill():
        os.kill(os.getpid(), signal.SIGINT)

    loop.create_task(_async_kill())
    loop.run_until_complete(future)

    assert instance.stop is True 
Example 17
Project: tomodachi   Author: kalaspuff   File: test_non_packaged_imported_service.py    License: MIT License 6 votes vote down vote up
def test_non_named_same_named_sub_service(monkeypatch: Any, capsys: Any, loop: Any) -> None:
    services, future = start_service('tests/services/test-copy/test-copy.py', monkeypatch)

    assert services is not None
    assert len(services) == 1
    instance = services.get('test_dummy')
    assert instance is not None
    assert instance.start is True
    assert instance.started is True
    assert instance.stop is False

    async def _async_kill():
        os.kill(os.getpid(), signal.SIGINT)

    loop.create_task(_async_kill())
    loop.run_until_complete(future)

    assert instance.stop is True 
Example 18
Project: tomodachi   Author: kalaspuff   File: test_protocol.py    License: MIT License 6 votes vote down vote up
def test_protobuf_base_bad_proto_class(monkeypatch: Any, capsys: Any, loop: Any) -> None:
    services, future = start_service('tests/services/dummy_protobuf_service.py', monkeypatch)

    instance = services.get('test_dummy_protobuf')

    async def _async() -> None:
        data = Person()
        data.name = 'John Doe'
        data.id = '12'
        json_message = await instance.message_protocol.build_message(instance, 'topic', data)
        await instance.message_protocol.parse_message(json_message, str)

    with pytest.raises(AttributeError):
        loop.run_until_complete(_async())

    async def _async_kill():
        os.kill(os.getpid(), signal.SIGINT)

    loop.create_task(_async_kill())
    loop.run_until_complete(future) 
Example 19
Project: tomodachi   Author: kalaspuff   File: test_protocol.py    License: MIT License 6 votes vote down vote up
def test_protobuf_validation_no_proto_class(monkeypatch: Any, capsys: Any, loop: Any) -> None:
    services, future = start_service('tests/services/dummy_protobuf_service.py', monkeypatch)

    instance = services.get('test_dummy_protobuf')

    async def _async() -> None:
        instance.message_protocol.validate()

    with pytest.raises(Exception):
        loop.run_until_complete(_async())

    async def _async_kill():
        os.kill(os.getpid(), signal.SIGINT)

    loop.create_task(_async_kill())
    loop.run_until_complete(future) 
Example 20
Project: tomodachi   Author: kalaspuff   File: test_protocol.py    License: MIT License 6 votes vote down vote up
def test_protobuf_validation_bad_proto_class(monkeypatch: Any, capsys: Any, loop: Any) -> None:
    services, future = start_service('tests/services/dummy_protobuf_service.py', monkeypatch)

    instance = services.get('test_dummy_protobuf')

    async def _async() -> None:
        instance.message_protocol.validate(proto_class=str)

    with pytest.raises(Exception):
        loop.run_until_complete(_async())

    async def _async_kill():
        os.kill(os.getpid(), signal.SIGINT)

    loop.create_task(_async_kill())
    loop.run_until_complete(future) 
Example 21
Project: tomodachi   Author: kalaspuff   File: test_protocol.py    License: MIT License 6 votes vote down vote up
def test_protobuf_object_validation_function(monkeypatch: Any, capsys: Any, loop: Any) -> None:
    services, future = start_service(
        'tests/services/dummy_protobuf_service.py', monkeypatch)

    instance = services.get('test_dummy_protobuf')

    def test_validator(person: Person) -> None:
        validate_field_regex(person.name, r'^[a-zA-Z ]+$')

    async def _async() -> None:
        data = Person()
        data.name = 'John Doe'
        data.id = '12'
        protobuf_message = await instance.message_protocol.build_message(
            instance, 'topic', data)
        await instance.message_protocol.parse_message(
            protobuf_message, Person, test_validator)

    loop.run_until_complete(_async())

    async def _async_kill():
        os.kill(os.getpid(), signal.SIGINT)

    loop.create_task(_async_kill())
    loop.run_until_complete(future) 
Example 22
Project: gated-graph-transformer-network   Author: hexahedria   File: graceful_interrupt.py    License: MIT License 5 votes vote down vote up
def __init__(self, sig=signal.SIGINT):
        self.sig = sig 
Example 23
Project: Random-Erasing   Author: zhunzhong07   File: helpers.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super(SigIntMixin, self).__init__(*args, **kwargs)
        signal(SIGINT, self._sigint_handler) 
Example 24
Project: tracker_project   Author: abarto   File: socketio_runserver.py    License: MIT License 5 votes vote down vote up
def reload_watcher():
    global RELOAD
    while True:
        RELOAD = code_changed()
        if RELOAD:
            kill(getpid(), SIGINT)
        sleep(1) 
Example 25
Project: testing.postgresql   Author: tk0miya   File: postgresql.py    License: Apache License 2.0 5 votes vote down vote up
def terminate(self, *args):
        # send SIGINT instead of SIGTERM
        super(Postgresql, self).terminate(signal.SIGINT if os.name != 'nt' else None) 
Example 26
Project: sanic   Author: huge-success   File: test_signal_handlers.py    License: MIT License 5 votes vote down vote up
def test_windows_workaround():
    """Test Windows workaround (on any other OS)"""
    # At least some code coverage, even though this test doesn't work on
    # Windows...
    class MockApp:
        def __init__(self):
            self.is_stopping = False

        def stop(self):
            assert not self.is_stopping
            self.is_stopping = True

        def add_task(self, func):
            loop = asyncio.get_event_loop()
            self.stay_active_task = loop.create_task(func(self))

    async def atest(stop_first):
        app = MockApp()
        ctrlc_workaround_for_windows(app)
        await asyncio.sleep(0.05)
        if stop_first:
            app.stop()
            await asyncio.sleep(0.2)
        assert app.is_stopping == stop_first
        # First Ctrl+C: should call app.stop() within 0.1 seconds
        os.kill(os.getpid(), signal.SIGINT)
        await asyncio.sleep(0.2)
        assert app.is_stopping
        assert app.stay_active_task.result() == None
        # Second Ctrl+C should raise
        with pytest.raises(KeyboardInterrupt):
            os.kill(os.getpid(), signal.SIGINT)
        return "OK"

    # Run in our private loop
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    res = loop.run_until_complete(atest(False))
    assert res == "OK"
    res = loop.run_until_complete(atest(True))
    assert res == "OK" 
Example 27
Project: sanic   Author: huge-success   File: worker.py    License: MIT License 5 votes vote down vote up
def init_signals(self):
        # Set up signals through the event loop API.

        self.loop.add_signal_handler(
            signal.SIGQUIT, self.handle_quit, signal.SIGQUIT, None
        )

        self.loop.add_signal_handler(
            signal.SIGTERM, self.handle_exit, signal.SIGTERM, None
        )

        self.loop.add_signal_handler(
            signal.SIGINT, self.handle_quit, signal.SIGINT, None
        )

        self.loop.add_signal_handler(
            signal.SIGWINCH, self.handle_winch, signal.SIGWINCH, None
        )

        self.loop.add_signal_handler(
            signal.SIGUSR1, self.handle_usr1, signal.SIGUSR1, None
        )

        self.loop.add_signal_handler(
            signal.SIGABRT, self.handle_abort, signal.SIGABRT, None
        )

        # Don't let SIGTERM and SIGUSR1 disturb active requests
        # by interrupting system calls
        signal.siginterrupt(signal.SIGTERM, False)
        signal.siginterrupt(signal.SIGUSR1, False) 
Example 28
Project: jawfish   Author: war-and-code   File: test_break.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        self._default_handler = signal.getsignal(signal.SIGINT) 
Example 29
Project: jawfish   Author: war-and-code   File: test_break.py    License: MIT License 5 votes vote down vote up
def tearDown(self):
        signal.signal(signal.SIGINT, self._default_handler)
        unittest.signals._results = weakref.WeakKeyDictionary()
        unittest.signals._interrupt_handler = None 
Example 30
Project: jawfish   Author: war-and-code   File: test_break.py    License: MIT License 5 votes vote down vote up
def testInstallHandler(self):
        default_handler = signal.getsignal(signal.SIGINT)
        unittest.installHandler()
        self.assertNotEqual(signal.getsignal(signal.SIGINT), default_handler)

        try:
            pid = os.getpid()
            os.kill(pid, signal.SIGINT)
        except KeyboardInterrupt:
            self.fail("KeyboardInterrupt not handled")

        self.assertTrue(unittest.signals._interrupt_handler.called)