Vinicius Gambi
09/27/2023, 5:55 PMMarvin
09/27/2023, 5:56 PMpython
import signal
import sys
def signal_handler(sig, frame):
print('You pressed Ctrl+C!')
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
signal.pause()
In this example, the signal_handler function will be called when a SIGINT (which is what gets sent when you press Ctrl+C) is received. You could replace signal.SIGINT with signal.SIGTERM to handle SIGTERM signals instead.
However, it's important to note that you can't catch a SIGKILL signal. The operating system doesn't allow it, because SIGKILL is meant to be a surefire way to terminate a program when all else fails.
As for detecting a systemctl stop operation from within the process, it depends on how your service is set up. If it's a systemd service, systemctl stop will send a SIGTERM signal to your process. So, you can set up a signal handler for SIGTERM as shown above.
Remember, though, that handling these signals doesn't prevent your program from being terminated. It just allows your program to do something (like clean up resources) before it gets shut down.Vinicius Gambi
09/27/2023, 5:57 PMMarvin
09/27/2023, 5:57 PMon_failure and on_success task event handlers to perform actions when a task fails or completes successfully.
But remember, I'm just a robot with a brain the size of a planet, so what do I know?Vinicius Gambi
09/27/2023, 6:00 PMMarvin
09/27/2023, 6:01 PMon_failure event handler in Prefect:
python
from prefect import task, Flow
@task
def might_fail(x):
if x < 0:
raise ValueError("x must be non-negative")
return x ** 0.5
@task
def handle_failure(task, state):
print(f"Oh dear, task {task} failed with state {state}")
might_fail.on_failure = handle_failure
with Flow("My Flow") as flow:
result = might_fail(-1)
In this example, might_fail is a task that will fail if its input is less than 0. The handle_failure task is set as the on_failure handler for might_fail, which means it will be called if might_fail fails.
When handle_failure is called, it's passed two arguments: the task that failed, and the state of the task when it failed. In this case, it just prints out a message, but you could do anything you want in the failure handler.
Remember, though, that the universe is vast and indifferent, and your tasks will fail whether you handle their failures or not. But I suppose it's the effort that counts.