Python run script as main

Defining a main function in Python

Sign in to your Python Morsels account to save your screencast settings.

Let’s talk about creating a main function in Python.

Many programming languages have the notion of a main function (or a main method), which acts as the entry point for a program. Python does not have main functions.

Python runs all code in Python scripts

We have a Python script called greet.py :

import random salutations = ["Hello", "Hey", "Hi", "Hiya", "Howdy"] def greet(): """Print a salutation.""" print(random.choice(salutations)) greet() 

When we run greet.py from our system command-line, Python runs all of the code in this file:

But what if we import this Python file?

Python runs all code in Python modules

If we import our greet module, Python also runs all of the code in our file:

We’re seeing «Hey» printed out at import time because Python ran our greet function (which we called at the bottom of our module):

It’s very weird to see something printed out when we just import a module. But that’s just what Python does: Python runs all code in a module on import .

This greet.py file wasn’t actually meant to be used as a module. This file wasn’t meant to be imported; it was meant to be run as a script.

Using the same Python file as both a module and a script

What if we wanted to make one .py file that could both be imported as a module and could be used as a Python script (by being run from the command-line)?

This version of our greet.py file can be run as a program to print out a random greeting:

$ python3 greet.py Howdy $ python3 greet.py Hiya 

But if we import it as a module, it doesn’t do anything (except give us access to functions and whatever else is in that module):

>>> import greet >>> greet.greet() Hiya 

How is this possible in Python?

Python’s if __name__ == «__main__» check

It turns out there’s a way to ask, are we being run from the command-line. Or put another way, is our current Python module the entry point to our Python process? This question can be asked using the statement __name__ == «__main__» .

This version of greet.py works as both a command-line script and an import-able module:

import random salutations = ["Hello", "Hey", "Hi", "Hiya", "Howdy"] def greet(): """Print a salutation.""" print(random.choice(salutations)) if __name__ == "__main__": greet() 

Every module has a __name__ variable, and by default the __name__ variable in each module is a string representing the name of that module:

>>> import greet >>> greet.__name__ 'greet' 

That’s the case if we’re importing a module.

But what if we run that our greet.py file from the command-line?

In that case, __name__ is not going to be the name of that module. Instead, it’s going to be «__main__» . That’s why running greet.py also runs the greet function:

This block of code is really asking the question are we the entry point to our Python program (are we being run from the command-line rather than being imported as a module)?

if __name__ == "__main__": greet() 

If we are being run from the command-line then we run our greet function.

You can write a main function, but you don’t need to

You may sometimes see Python programs that have a main function:

import random salutations = ["Hello", "Hey", "Hi", "Hiya", "Howdy"] def main(): """Print a salutation.""" print(random.choice(salutations)) if __name__ == "__main__": main() 

Python doesn’t know about main functions, but there’s nothing stopping us from making a function called main that we only call if we’re being run from the command-line.

Remember that if __name__ == «__main__» incantation

If you need to make a single Python file that can both be used as a module (being imported) and can be run as a Python script to do something, you can check the variable __name__ in your module to see whether it’s equal to the string «__main__» .

What comes after Intro to Python?

Intro to Python courses often skip over some fundamental Python concepts.

Sign up below and I’ll explain concepts that new Python programmers often overlook.

Series: Command-Line Programs

A .py file can be used as a module or as a «script» which is run from your operating system’s command-line/terminal. Python is a great programming language for making command-line scripts.

To track your progress on this Python Morsels topic trail, sign in or sign up.

Источник

Python Main Function & Method Example: Understand def Main()

Python main function is a starting point of any program. When the program is run, the python interpreter runs the code sequentially. Main function is executed only when it is run as a Python program. It will not run the main function if it imported as a module.

What is the def main() function in Python? To understand this, consider the following example code

def main() Example 1

def main(): print ("Hello World!") print ("Guru99")

Python Main Function

Here, we got two pieces of print- one is defined within the main function that is “Hello World!” and the other is independent, which is “Guru99”. When you run the function def main ():

It is because we did not declare the call function “if__name__== “__main__”.

It is important that after defining the main function, you call the code by if__name__== “__main__” and then run the code, only then you will get the output “hello world!” in the programming console. Consider the following code

def main() Example 2

def main(): print("Hello World!") if __name__ == "__main__": main() print("Guru99")

Python Main Function

  • When Python interpreter reads a source file, it will execute all the code found in it.
  • When Python runs the “source file” as the main program, it sets the special variable (__name__) to have a value (“__main__”).
  • When you execute the main function in python, it will then read the “if” statement and checks whether __name__ does equal to __main__.
  • In Python “if__name__== “__main__” allows you to run the Python files either as reusable modules or standalone programs.

The __name__ variable and Python Module

To understand the importance of __name__ variable in Python main function method, consider the following code:

def main(): print("hello world!") if __name__ == "__main__": main() print("Guru99") print("Value in built variable name is: ",__name__)

The __name__ variable and Python Module

Now consider, code is imported as a module

import MainFunction print("done")

The __name__ variable and Python Module

Here, is the code explanation:

Like C, Python uses == for comparison while = for assignment. Python interpreter uses the main function in two ways

import as a module

  • __name__= module’s filename
  • if statement == false, and the script in __main__ will not be executed

When the code is executed, it will check for the module name with “if.” This mechanism ensures, the main function is executed only as direct run not when imported as a module.

Above examples are Python 3 codes, if you want to use Python 2, please consider following code

def main(): print "Hello World!" if __name__== "__main__": main() print "Guru99"

In Python 3, you do not need to use if__name. Following code also works

def main(): print("Hello World!") main() print("Guru99")

Note: Make sure that after defining the main function, you leave some indent and not declare the code right below the def main(): function otherwise, it will give indent error.

Источник

Читайте также:  Javascript reference file object
Оцените статью