Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to Call the main() Function of an Imported Module in Python
Next article icon

How to Call the main() Function of an Imported Module in Python

Last Updated : 22 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given an imported module and our task is to call the main() function of that module after importing it in Python. In this article, we will see how to call the main() of an imported module in Python.

Call the main() Function of an Imported Module in Python

Below, are the code methods of how to call the main() of an imported module in Python:

  • Import and Directly Call main()
  • Using if __name__ == "__main__"
  • Using getattr() to Dynamically Call main()

Import and Directly Call main() Function in Python

The most straightforward method involves importing the module and directly calling its main() function. Let's consider a module named example_module.py with the following structure:

example_module.py: below Python code defines a `main()` function in the module `example_module.py` and executes it only if the module is run directly, not when imported as a module into another script.

Python3
# example_module.py def main():     print("Executing main() in example_module")  if __name__ == "__main__":     main() 

main.py : below, code imports the module named `example_module` and directly calls its main() function, executing the code within the main() function of the imported module.

Python3
# main_script.py import example_module  # Call the main() function directly example_module.main() 

Output

Executing main() in example_module 

Using if __name__ == "__main__" in Python

In some cases, the main() function may include command-line argument parsing or other logic that should only be executed when the module is run as the main program. To accommodate this, use the following structure in example_module.py:

example_module.py: below Python code defines a main() function in the module example_module.py and executes it only if the module is run directly, not when imported as a module into another script.

Python3
# example_module.py def main():     print("Executing main() in example_module")  if __name__ == "__main__":     main() 

main.py: Below, code imports the module named example_module and calls its main() function only when the script is run directly, not when imported as a module into another script. The if __name__ == "__main__": condition ensures selective execution.

Python3
# main_script.py import example_module  # Call the main() function using if __name__ == "__main__" if __name__ == "__main__":     example_module.main() 

Output

Executing main() in example_module

Using getattr() to Dynamically Call main() Function

For more dynamic scenarios, where the module name or function to call may change at runtime, you can use the getattr() function. Assume you have a variable module_name containing the name of the module to import:

example_module.py: below Python code defines a main() function in the module example_module.py and executes it only if the module is run directly, not when imported as a module into another script.

Python3
# example_module.py def main():     print("Executing main() in example_module")  if __name__ == "__main__":     main() 

main.py : Below, code dynamically imports a module named "example_module" and dynamically calls its "main()" function using the getattr() function, allowing for flexibility in specifying module and function names at runtime.

Python3
# main_script.py module_name = "example_module" main_function_name = "main"  # Import the module dynamically example_module = __import__(module_name)  # Dynamically call the main() function getattr(example_module, main_function_name)() 

Output

Executing main() in example_module

Conclusion

In conclusion, Calling the main() function of an imported module in Python can be achieved through various methods, depending on your specific requirements. Whether you prefer a direct approach, utilize the if __name__ == "__main__" condition, or dynamically call functions using getattr(), Python offers flexibility to suit your coding style and project needs.


Next Article
How to Call the main() Function of an Imported Module in Python

H

harishnarayana
Improve
Article Tags :
  • Python
  • Python Programs
  • python-file-handling
Practice Tags :
  • python

Similar Reads

    Can I call a function in Python from a print statement?
    Calling a function from a print statement is quite an easy task in Python Programming. It can be done when there is a simple function call, which also reduces the lines of code. In this article, we will learn how we can call a function from a print statement.Calling a Function Inside print()In this
    1 min read
    How to Import Other Python Files?
    We have a task of how to import other Python Files. In this article, we will see how to import other Python Files. Python's modular and reusable nature is one of its strengths, allowing developers to organize their code into separate files and modules. Importing files in Python enables you to reuse
    3 min read
    How Can I Make One Python File Run Another File?
    In Python programming, there often arises the need to execute one Python file from within another. This could be for modularity, reusability, or simply for the sake of organization. In this article, we will explore different approaches to achieve this task, each with its advantages and use cases. Ma
    2 min read
    Os Module Vs. Sys Module In Python
    Python provides a lot of libraries to interact with the development environment. If you need help using the OS and Sys Module in Python, you have landed in the right place. This article covers a detailed explanation of the OS and Sys Module including their comparison. By the end of this article, you
    5 min read
    How to Run Another Python script with Arguments in Python
    Running a Python script from another script and passing arguments allows you to modularize code and enhance reusability. This process involves using a subprocess or os module to execute the external script, and passing arguments can be achieved by appending them to the command line. In this article,
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences