Search code examples
pythonfunctionmodulecall

In Python, how can a function of a script be called from within a module that is imported by that script?


I have a set of scripts that each have their own specialized termination functions. Many of these scripts call a module of general functions. Some of these module functions should direct the script to terminate.

I am aware that the standard approach would be to have the module functions return values that are interpreted by the scripts (in this case, in a way that causes the scripts to terminate), but I would like to know how to call the terminate function of a script from the module.


Solution

  • Your scripts should register their special termination functions using atexit. (See https://docs.python.org/3.5/library/atexit.html)

    Then they will be called no matter why it terminates. Your general module can then just use sys.exit().