Understanding Python Signals and Modules

I am trying to speed up with Python, trying to replace it with C. I am having a problem with exchanging data between modules or, rather, with my understanding of all this. I have a signal module that is simplified:

import sys, signal

sigterm_caught = False

def SignalHandler(signum, stackframe):
  if signum == signal.SIGTERM:
    sigterm_caught = True
    sys.stdout.write("SIGTERM caught\n")

def SignalSetup():
  signal.signal(signal.SIGTERM, SignalHandler)

and my main code has this loop:

signals.SignalSetup()
while signals.sigterm_caught == False:
  sys.stdout.write("sigterm_caught=%s\n" % str(signals.sigterm_caught))
  time.sleep(5)

I start it and then kill the process, inside signal.py it receives the signal, sets sigterm_caught to True, but the loop in the main process does not see the change in the sigterm_caught value.

So (a) is my approach completely wrong for the Python path? (b) Am I doing something wrong trying to refer to variables in a module? and (c) should signals be handled differently, for example, by throwing an exception?

Addition: Is it better to handle signals by throwing an exception, or is my old C approach still valid?

+3
2

global :

def SignalHandler(signum, stackframe):
  global sigterm_caught
  if signum == signal.SIGTERM:
    sigterm_caught = True
    sys.stdout.write("SIGTERM caught\n")

Python , (, sigterm_caught) , , ; global , , Python ( ).

+7

, global:

sigterm_caught = False

def SignalHandler(signum, stackframe):
  global sigterm_caught
  if signum == signal.SIGTERM:
    sigterm_caught = True
    sys.stdout.write("SIGTERM caught\n")
+3

Source: https://habr.com/ru/post/1738347/


All Articles