Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Pass more than two arguments in signal

Tags:

python

signals

I know what when I use signals there are two arguments (signum and frame).

But what if I want to send more? For example: object for self.

How can I do it?

example:

def terminate_handler(signum, frame, self):
    self.close()
signal.signal(signal.SIGINT, terminate_handler, object)

EDIT: I found out the solution I worte on the fly, when I thought it would not work, actualy work. I had no Idea it will work

def terminate_handler(self, signum, frame):
        self.close()
signal.signal(signal.SIGINT, terminate_handler, object)
like image 256
Guy Markman Avatar asked Jun 05 '26 01:06

Guy Markman


2 Answers

Why not

def terminate_handler(self, signum, frame):
    self.close()
signal.signal(signal.SIGINT, partial(terminate_handler, obj))

Here is a fully working example (kill -2 ...)

import signal, os, sys
from functools import partial
from time import sleep
def terminate_handler(self, signum, frame):
    print('terminate_handler:', self, signum)
    sys.exit(0)
signal.signal(signal.SIGINT, partial(terminate_handler, 'foo'))
while True:
    sleep(1)
like image 61
Gribouillis Avatar answered Jun 08 '26 00:06

Gribouillis


Another option is to use a lambda function, and pass the variables in the closure:

import signal
import time

def real_handler(signum, frame, arg1):
  print(arg1)
  exit(1)

signal.signal(signal.SIGINT, lambda signum, frame: real_handler(signum, frame, 'foo'))

while True:
  time.sleep(1)
like image 41
user2233706 Avatar answered Jun 08 '26 00:06

user2233706



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!