I am trying to create forms in Dynamo based on user selection, and I want the script to stop executing once the user closes or cancels the form.
Currently, I am using sys.exit() to terminate the script when the user clicks Close or Cancel, but this is causing an error inside the Python node.
I need a proper way to safely stop or exit the script execution in Dynamo when the form is closed or cancelled.
What error? If you’re referring to the warning status, this is by design and likely a good thing for you as users may not know why things stopped working without it. I would recommend changing it to sys.exit(“/r/r/tInput form canceled/r/r”) so the reason is clear.
Indeed, you are quite right; it is, in fact, a warning.
As a workaround, you can implement a ContextManager to manage the workflow with ‘SystemExit’ BaseExceptions .
import sys
import clr
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *
class ErrorContextManager:
def __init__(self):
pass
def __enter__(self):
print("Context Successfully Started")
return self
def __exit__(self, exc_type, exc_value, exc_tb):
if exc_type is None:
print("Successfully Exited From Context\n")
return False
if issubclass(exc_type, SystemExit):
return True
line_no = exc_tb.tb_lineno if exc_tb else "unknown"
error_msg = f"{exc_value} at line {line_no}"
exc_value.args = (error_msg,)
return False
with ErrorContextManager() as c:
print(1)
sys.exit()
print(2)
OUT = 0
Personally, I handle this using simple if statements