title: Purpose of 'if __name__ == "__main__":'
body: <p>I am trying to understand some code I found which reads command line arguments (attached below). My concern is what purpose of the <code>"if __name__ == __main__"</code>line is...</p>
  
  <p>Why would I use that line instead of just using the code below, <code>main(sys.argv[1:])</code>. What extra use does it provide?</p>
  
  <pre><code>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 &lt;inputfile&gt; -o &lt;outputfile&gt;'
        sys.exit(2)
     for opt, arg in opts:
        if opt == '-h':
           print 'test.py -i &lt;inputfile&gt; -o &lt;outputfile&gt;'
           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:])
  </code></pre>