Can I raise a signal from python?

Question:

The topic basically tells what I want to to.

I read the documentation, which tells me how to handle signals but not how I can do signalling by myself.

Thanks!

Asked By: Simbi

||

Answers:

Use os.kill. For example, to send SIGUSR1 to your own process, use

import os,signal
os.kill(os.getpid(), signal.SIGUSR1)
Answered By: phihag

You can use the os.kill method. Since Python 2.7 it should work (did not test it myself) on both Unix and Windows, although it needs to be called with different parameters:

import os, signal

os.kill(pid, signal.SIGHUP) # Unix version only...
Answered By: helmbert

Just proposing a different method, if its on windows:

import ctypes
ucrtbase = ctypes.CDLL('ucrtbase')
c_raise = ucrtbase['raise']
c_raise(some_signal)

some_signal can be any signal num, eg signal.SIGINT.

Answered By: Ronen Ness

Directly with the signal package (new in version 3.8). For instance:

import signal
signal.raise_signal( signal.SIGINT )

Reference: https://docs.python.org/3/library/signal.html#signal.raise_signal

Answered By: Campa
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.