class TerminateProgramException(Exception):
pass
if compare_data:
logging.info(
f"compare_srvice common_compare end,hit cache compare_data:{compare_data},request_data:{request_data}"
)
print(compare_data)
raise TerminateProgramException("Terminating program intentionally")
# Elsewhere in your main execution or caller function
try:
# Your calling code here
pass
except TerminateProgramException as e:
logging.info(str(e))
sys.exit()
Using Return Statements:
使用返回语句来退出当前函数然后逐级向上返回,直至退出主函数。
python
def main_function():
if compare_data:
logging.info(
f"compare_srvice common_compare end,hit cache compare_data:{compare_data},request_data:{request_data}"
)
print(compare_data)
return # Exit the function
if __name__ == "__main__":
main_function()
logging.info("Program finished maybe with cache hit")
Check Execution Context:
确保 sys.exit() 是在合适的上下文中调用的,比如在主线程或者不被其他框架捕获的环境中。
python
if compare_data:
logging.info(
f"compare_srvice common_compare end,hit cache compare_data:{compare_data},request_data:{request_data}"
)
print(compare_data)
if threading.current_thread() == threading.main_thread():
sys.exit()
else:
raise SystemExit("Exit from non-main thread")
Using a Control Variable:
使用一个控制变量来控制程序的流程,适用于复杂的逻辑控制需要。
python
terminate_program = False
if compare_data:
logging.info(
f"compare_srvice common_compare end,hit cache compare_data:{compare_data},request_data:{request_data}"
)
print(compare_data)
terminate_program = True
if terminate_program:
sys.exit()
def greet(name, age, city):
print(f"Hello, {name}. You are {age} years old and live in {city}.")
person_info = {
"name": "Alice",
"age": 30,
"city": "New York"
}
greet(**person_info)
输出:
code
Hello, Alice. You are 30 years old and live in New York.
class DynamicObject:
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
obj = DynamicObject(name="Alice", age=30, city="New York")
print(obj.name) # Alice
print(obj.age) # 30
print(obj.city) # New York