Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Purpose of 'if __name__ == "__main__":' [duplicate]

I am trying to understand some code I found which reads command line arguments (attached below). My concern is what purpose of the "if __name__ == __main__"line is...

Why would I use that line instead of just using the code below, main(sys.argv[1:]). What extra use does it provide?

import sys, getopt

def main(argv):
   inputfile = ''
   outputfile = ''
   try:
      opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
   except getopt.GetoptError:
      print 'test.py -i <inputfile> -o <outputfile>'
      sys.exit(2)
   for opt, arg in opts:
      if opt == '-h':
         print 'test.py -i <inputfile> -o <outputfile>'
         sys.exit()
      elif opt in ("-i", "--ifile"):
         inputfile = arg
      elif opt in ("-o", "--ofile"):
         outputfile = arg
   print 'Input file is "', inputfile
   print 'Output file is "', outputfile

if __name__ == "__main__":
   main(sys.argv[1:])
like image 852
Chris Headleand Avatar asked Apr 10 '14 22:04

Chris Headleand


People also ask

Why do we need if name == Main?

We can use an if __name__ == "__main__" block to allow or prevent parts of code from being run when the modules are imported. When the Python interpreter reads a file, the __name__ variable is set as __main__ if the module being run, or as the module's name if it is imported.

What is the purpose of __ name __?

__name__ is a built-in variable which evaluates to the name of the current module. Thus it can be used to check whether the current script is being run on its own or being imported somewhere else by combining it with if statement, as shown below. Consider two separate files File1 and File2.

What is the purpose of __ main __ in Python?

__main__ is the name of the environment where top-level code is run. “Top-level code” is the first user-specified Python module that starts running. It's “top-level” because it imports all other modules that the program needs.

What is the value of __ name __?

The __name__ variable in the app.py set to the module name which is billing . In this case the value of the __name__ variable is '__main__' inside the billing.py . Therefore, the __name__ variable allows you to check when the file is executed directly or imported as a module.


4 Answers

Well, imagine that someone else wants to use the functions in your module in their own program. They import your module... and it starts doing its own thing!

With the if __name__ == "__main__", this doesn't happen. Your module only "does its thing" if it's run as the main module. Otherwise it behaves like a library. It encourages code reuse by making it easier.

(As Sheng mentions, you may want to import the module into another script yourself for testing purposes.)

like image 199
kindall Avatar answered Nov 15 '22 20:11

kindall


The if __name__ == '__main__' convention in Python is intended to allow you to write code that can be run directly, or imported.

If you import it, that if block is not executed. If you run python.exe myscript.py it is.

like image 45
g.d.d.c Avatar answered Nov 15 '22 22:11

g.d.d.c


It is for unit test proposes.

If you are running this script directly, it will execute the if block. So you could do some unit test work here. But if you are importing this file as a module, you do not want this part to execute.

It is similar to the main function in Java. In every Java class, you could have a main function for unit test. But the class is imported/used as a module, the main function would not be executed.

Generally, if you're using this script directly, it will run the if block. Otherwise, someone would like to use this file as a library of function/class, and the test case name makes sure this code would not bother users.

like image 37
Sheng Avatar answered Nov 15 '22 20:11

Sheng


This is the idiomatic way to tell whether the Python module was executed as a script, or imported from another module. You will only enter the if __name__ == "__main__" block if the file was executed as a script (aka, it is the main module).

like image 32
Andrew Clark Avatar answered Nov 15 '22 21:11

Andrew Clark