Include conditional code in your Python modules to handle cases where a module can function as the top-level environment or an imported module.

Python is designed in such a way that when the top-level Python module imports a second Python module, the interpreter evaluates and executes the statements in the second module. With the Python Adapter in TestStand, the interpreter treats TestStand as the top-level environment. TestStand imports the specified module at certain events to determine if the module is valid or not, and to determine the contents of the module. Therefore, any Python module you specify in a Python Adapter step will run when TestStand loads the module, even when the sequence is not executing.

To prevent the interpreter from executing Python code when it imports a module, encapsulate Python module code within the following statement:

if __name__ == "__main__":

When a Python module runs directly as the top-level script, the interpreter sets the variable __name__ to __main__. For imported modules, the interpreter sets the variable __name__ to the name of the module. Encapsulating executable code within the conditional statement ensures that the interpreter will check whether the module code is running in the __main__ environment, and if not, the code will not execute on import.

Refer to Python documentation for more information about using the __name__ variable.