Home >Backend Development >Python Tutorial >How to Prevent Python Code Execution During Module Import?

How to Prevent Python Code Execution During Module Import?

Barbara Streisand
Barbara StreisandOriginal
2024-12-20 20:09:11150browse

How to Prevent Python Code Execution During Module Import?

How to Prevent Python from Executing Code on Import

You've implemented a Python program that allows for two methods of execution: an interactive mode with user input (main.py) and a batch mode that processes input from a file (batch.py). Importing main.py into batch.py, however, triggers the execution of code in main.py, leading to errors.

Reason:

In Python, keywords like class and def represent statements that are executed when encountered. These statements are not mere declarations but active statements, a design feature that ensures the existence of content in your module.

Solution:

The Pythonic approach to addressing this issue is to adopt the following structure:

# Place any code that should run regardless of execution mode here (e.g., class/def)

def main():
    pass

if __name__ == "__main__":
    # Code that is only executed when called as "python main.py"
    main()

With this approach, code placed outside the main function will run regardless of how the script is called (directly or through import). Code within the main function will only execute when the script is run directly (python main.py).

The above is the detailed content of How to Prevent Python Code Execution During Module Import?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn