Python main() functions

  • Post author:
  • Post category:
  • Post comments:0 Comments
  • Post last modified:September 16, 2005

Guido van Rossum라는 사람이 쓴 Python main() functions라는 문서는 Python에서 EntryPoint를 어떻게 작성할 것인지에 대한 흥미로운 제안을 하고 있습니다. 우선 아래의 두 소스 코드를 봅시다.

최초의 소스코드

import sys
import getopt

def main():
    # parse command line options
    try:
        opts, args = getopt.getopt(sys.argv[1:], "h", ["help"])
    except getopt.error, msg:
        print msg
        print "for help use --help"
        sys.exit(2)
    # process options
    for o, a in opts:
        if o in ("-h", "--help"):
            print __doc__
            sys.exit(0)
    # process arguments
    for arg in args:
        process(arg) # process() is defined elsewhere

if __name__ == "__main__":
    main()

수정한 소스코드

import sys
import getopt

class Usage(Exception):
    def __init__(self, msg):
        self.msg = msg

def main(argv=None):
    if argv is None:
        argv = sys.argv
    try:
        try:
            opts, args = getopt.getopt(argv[1:], "h", ["help"])
        except getopt.error, msg:
             raise Usage(msg)
        # more code, unchanged
    except Usage, err:
        print >>sys.stderr, err.msg
        print >>sys.stderr, "for help use --help"
        return 2

if __name__ == "__main__":
    sys.exit(main())
  • def main():main(argv=None):와 같이 바뀌었습니다. 이는 Interactive Python prompt에서 main 함수를 호출할 수 있도록 합니다. main(argv=sys.argv):와 같이 바꾸는 방법도 고려해볼만 합니다. 하지만 main 함수가 호출될 때마다 sys.argv 값이 변할 수 있기 때문에 전자가 낫습니다.
  • main 함수 내에서 sys.exit()를 호출한다면 Interactive Python이 종료되어 버립니다. 이것은 아주 짜증나는 일일 것입니다. 그러므로 main 함수는 exit status 값만 반환하도록 작성되어야 합니다. 이것이 sys.exit(main())의 의미입니다.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.