Monday 27 February 2017

python - Purpose of 'if __name__ == "__main__":'




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 -o '

sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'test.py -i -o '
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:])

Answer



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.)


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...