3

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)
Guy Markman
  • 426
  • 1
  • 4
  • 14
  • Man, you're writing the method wrong. Actually it's the first argument. That's the first thing you learn when you start using OOP in python. –  Dec 07 '16 at 20:56

2 Answers2

3

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)
Gribouillis
  • 2,230
  • 1
  • 9
  • 14
  • Yeah, cos they're writing the method wrong. Actually it's the first argument. That's the first thing you learn when you start using OOP in python. –  Dec 07 '16 at 20:56
  • I tried using what you did, but I get the next error terminate_handler() takes exactly 3 arguments (4 given) – Guy Markman Dec 07 '16 at 21:07
2

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)
user2233706
  • 6,148
  • 5
  • 44
  • 86