Guy Markman
Guy Markman

Reputation: 446

Python: Pass more than two arguments in signal

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)

Upvotes: 3

Views: 2613

Answers (2)

user2233706
user2233706

Reputation: 7207

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)

Upvotes: 2

Gribouillis
Gribouillis

Reputation: 2220

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)

Upvotes: 3

Related Questions