main

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • fatwallet961@yahoo.com

    #1

    main

    is the main function in python is exact compare to Java main method?

    all execution start in main which may takes arguments?

    like the follow example script -

    def main(argv):

    =============== ===============

    and what is
    __name__
    __main__

    use for in terms of Java?

    thanks






    =============== ===============
    #!/usr/bin/env python

    """
    Preprocess a file.

    Command Line Usage:
    preprocess [<options>...] <infile>

    Options:
    -h, --help Print this help and exit.
    -v, --verbose Give verbose output for errors.

    -o <outfile Write output to the given file instead of to
    stdout.
    -D <define Define a variable for preprocessing. <define>
    can simply be a variable name (in which case
    it
    will be true) or it can be of the form
    <var>=<val>. An attempt will be made to
    convert
    <valto an integer so "-D FOO=0" will create
    a
    false value.

    Module Usage:
    from preprocess import preprocess
    preprocess(infi le, outfile=sys.std out, defines={})

    The <infilecan be marked up with special preprocessor statement
    lines
    of the form:
    <comment-prefix<preproce ssor-stmt<comment-suffix>
    where the <comment-prefix/suffixare the native comment
    delimiters for
    that file type. Examples:
    <!-- #if FOO -->
    ...
    <!-- #endif -->

    # #if defined('FAV_CO LOR') and FAV_COLOR == "blue"
    ...
    # #elif FAV_COLOR == "red"
    ...
    # #else
    ...
    # #endif

    Preprocessor Syntax:
    - Valid statements:
    #define <var>[=<value>]
    #undef <var>
    #if <expr>
    #elif <expr>
    #else
    #endif
    #error <error string>
    where <expris any valid Python expression.
    - The expression after #if/elif may be a Python statement. It
    is an
    error to refer to a variable that has not been defined by a
    -D
    option.
    - Special built-in methods for expressions:
    defined(varName ) Return true if given variable is
    defined.
    """

    import os
    import sys
    import getopt
    import types
    import re
    import pprint
    import logging

    from contenttype import getContentType


    #---- exceptions
    class PreprocessError (Exception):
    def __init__(self, errmsg, file=None, lineno=None, line=None):
    self.errmsg = str(errmsg)
    self.file = file
    self.lineno = lineno
    self.line = line
    Exception.__ini t__(self, errmsg, file, lineno, line)
    def __str__(self):
    s = ""
    if self.file is not None:
    s += self.file + ":"
    if self.lineno is not None:
    s += str(self.lineno ) + ":"
    if self.file is not None or self.lineno is not None:
    s += " "
    s += self.errmsg
    return s


    #---- global data

    log = logging.getLogg er("preprocess" )

    # Comment delimiter info.
    # A mapping of content type to a list of 2-tuples defining the line
    # prefix and suffix for a comment.
    _commentGroups = {
    "Python": [ ('#', '') ],
    "Perl": [ ('#', '') ],
    "Tcl": [ ('#', '') ],
    "XML": [ ('<!--', '-->') ],
    "HTML": [ ('<!--', '-->') ],
    "Makefile": [ ('#', '') ],
    "JavaScript ": [ ('/*', '*/'), ('//', '') ],
    "CSS": [ ('/*', '*/') ],
    "C": [ ('/*', '*/') ],
    "C++": [ ('/*', '*/'), ('//', '') ],
    "IDL": [ ('/*', '*/'), ('//', '') ],
    "Text": [ ('#', '') ],
    }


    #---- internal support stuff

    def _evaluate(expr, defines):
    """Evaluate the given expression string with the given context."""
    try:
    rv = eval(expr, {'defined':lamb da v: v in defines}, defines)
    except Exception, ex:
    raise PreprocessError (str(ex), defines['__FILE__'],
    defines['__LINE__'])
    log.debug("eval uate %r -%s (defines=%r)", expr, rv, defines)
    return rv



    #---- module API

    def preprocess(infi le, outfile=sys.std out, defines={}):
    """Preproce ss the given file.

    "infile" is the input filename.
    "outfile" is the output filename or stream (default is
    sys.stdout).
    "defines" is a dictionary of defined variables that will be
    understood in preprocessor statements. Keys must be strings
    and,
    currently, only the truth value of any key's value matters.

    Returns the modified dictionary of defines or raises
    PreprocessError if
    there was some problem.
    """
    log.info("prepr ocess(infile=%r , outfile=%r, defines=%r)",
    infile, outfile, defines)

    # Determine the content type and comment info for the input file.
    contentType = getContentType( infile)
    if contentType is None:
    contentType = "Text"
    log.warn("defau lting content type for '%s' to '%s'",
    infile, contentType)
    try:
    cgs = _commentGroups[contentType]
    except KeyError:
    raise PreprocessError ("don't know comment delimiters for
    content "\
    "type '%s' (file '%s')"\
    % (contentType, infile))

    # Generate statement parsing regexes.
    stmts = ['#\s*(?P<op>if| elif|ifdef|ifnd ef)\s+(?P<expr> .*?)',
    '#\s*(?P<op>els e|endif)',
    '#\s*(?P<op>err or)\s+(?P<error >.*?)',
    '#\s*(?P<op>def ine)\s+(?P<var>[^\s]*?)(\s+(?P<val> .+?))?',
    '#\s*(?P<op>und ef)\s+(?P<var>[^\s]*?)']
    patterns = ['^\s*%s\s*%s\s* %s\s*$'
    % (re.escape(cg[0]), stmt, re.escape(cg[1]))
    for cg in cgs for stmt in stmts]
    stmtRes = [re.compile(p) for p in patterns]

    # Process the input file.
    fin = open(infile, 'r')
    if type(outfile) in types.StringTyp es:
    if os.path.exists( outfile):
    os.chmod(outfil e, 0777)
    os.remove(outfi le)
    fout = open(outfile, 'w')
    else:
    fout = outfile

    defines['__FILE__'] = infile
    SKIP, EMIT = range(2) # states
    states = [(EMIT, # a state is
    (<emit-or-skip-lines-in-this-section>,
    0, # <have-emitted-in-this-if-block>,
    0)] # <have-seen-'else'-in-this-if-block>)
    lineNum = 0
    for line in fin.readlines() :
    lineNum += 1
    log.debug("line %d: %r", lineNum, line)
    defines['__LINE__'] = lineNum

    # Is this line a preprocessor stmt line?
    for stmtRe in stmtRes:
    match = stmtRe.match(li ne)
    if match:
    break
    else:
    match = None

    if match:
    op = match.group("op ")
    log.debug("%r stmt (states: %r)", op, states)
    if op == "define":
    if states and states[-1][0] == SKIP: continue
    var, val = match.group("va r", "val")
    if val is None:
    val = None
    else:
    try:
    val = eval(val, {}, {})
    except:
    pass
    defines[var] = val
    elif op == "undef":
    if states and states[-1][0] == SKIP: continue
    var = match.group("va r")
    try:
    del defines[var]
    except KeyError:
    pass
    elif op in ("if", "ifdef", "ifndef"):
    if op == "if":
    expr = match.group("ex pr")
    elif op == "ifdef":
    expr = "defined('% s')" % match.group("ex pr")
    elif op == "ifndef":
    expr = "not defined('%s')" % match.group("ex pr")
    try:
    if states and states[-1][0] == SKIP:
    # Were are nested in a SKIP-portion of an
    if-block.
    states.append(( SKIP, 0, 0))
    elif _evaluate(expr, defines):
    states.append(( EMIT, 1, 0))
    else:
    states.append(( SKIP, 0, 0))
    except KeyError:
    raise PreprocessError ("use of undefined variable
    in "\
    "#%s stmt" % op,
    defines['__FILE__'],
    defines['__LINE__'], line)
    elif op == "elif":
    expr = match.group("ex pr")
    try:
    if states[-1][2]: # already had #else in this
    if-block
    raise PreprocessError ("illegal #elif after
    #else in "\
    "same #if block", defines['__FILE__'],
    defines['__LINE__'], line)
    elif states[-1][1]: # if have emitted in this
    if-block
    states[-1] = (SKIP, 1, 0)
    elif states[:-1] and states[-2][0] == SKIP:
    # Were are nested in a SKIP-portion of an
    if-block.
    states[-1] = (SKIP, 0, 0)
    elif _evaluate(expr, defines):
    states[-1] = (EMIT, 1, 0)
    else:
    states[-1] = (SKIP, 0, 0)
    except IndexError:
    raise PreprocessError ("#elif stmt without leading
    #if "\
    "stmt", defines['__FILE__'],
    defines['__LINE__'], line)
    elif op == "else":
    try:
    if states[-1][2]: # already had #else in this
    if-block
    raise PreprocessError ("illegal #else after
    #else in "\
    "same #if block", defines['__FILE__'],
    defines['__LINE__'], line)
    elif states[-1][1]: # if have emitted in this
    if-block
    states[-1] = (SKIP, 1, 1)
    elif states[:-1] and states[-2][0] == SKIP:
    # Were are nested in a SKIP-portion of an
    if-block.
    states[-1] = (SKIP, 0, 1)
    else:
    states[-1] = (EMIT, 1, 1)
    except IndexError:
    raise PreprocessError ("#else stmt without leading
    #if "\
    "stmt", defines['__FILE__'],
    defines['__LINE__'], line)
    elif op == "endif":
    try:
    states.pop()
    except IndexError:
    raise PreprocessError ("#endif stmt without leading
    #if"\
    "stmt", defines['__FILE__'],
    defines['__LINE__'], line)
    elif op == "error":
    if states and states[-1][0] == SKIP: continue
    error = match.group("er ror")
    raise PreprocessError ("#error: "+error,
    defines['__FILE__'],
    defines['__LINE__'], line)
    log.debug("stat es: %r", states)
    else:
    try:
    if states[-1][0] == EMIT:
    log.debug("emit line (%s)" % states[-1][1])
    fout.write(line )
    else:
    log.debug("skip line (%s)" % states[-1][1])
    except IndexError:
    raise PreprocessError ("superfluou s #endif before this
    line",
    defines['__FILE__'],
    defines['__LINE__'])
    if len(states) 1:
    raise PreprocessError ("unterminat ed #if block",
    defines['__FILE__'],
    defines['__LINE__'])
    elif len(states) < 1:
    raise PreprocessError ("superfluou s #endif on or before this
    line",
    defines['__FILE__'],
    defines['__LINE__'])

    if fout != outfile:
    fout.close()


    #---- mainline

    def main(argv):
    try:
    optlist, args = getopt.getopt(a rgv[1:], 'hvo:D:', ['help',
    'verbose'])
    except getopt.GetoptEr ror, msg:
    sys.stderr.writ e("preprocess : error: %s" % msg)
    sys.stderr.writ e("See 'preprocess --help'.\n")
    return 1
    outfile = sys.stdout
    defines = {}
    for opt, optarg in optlist:
    if opt in ('-h', '--help'):
    sys.stdout.writ e(__doc__)
    return 0
    elif opt in ('-v', '--verbose'):
    log.setLevel(lo gging.DEBUG)
    elif opt == '-o':
    outfile = optarg
    elif opt == '-D':
    if optarg.find('=' ) != -1:
    var, val = optarg.split('= ', 1)
    try:
    val = eval(val, {}, {})
    except:
    pass
    else:
    var, val = optarg, None
    defines[var] = val

    if len(args) != 1:
    sys.stderr.writ e("preprocess : error: incorrect number of "\
    "arguments: argv=%r\n" % argv)
    return 1
    else:
    infile = args[0]

    try:
    preprocess(infi le, outfile, defines)
    except PreprocessError , ex:
    sys.stderr.writ e("preprocess : error: %s\n" % str(ex))

    if __name__ == "__main__":
    sys.exit( main(sys.argv) )

  • Paddy

    #2
    Re: main

    On Feb 3, 4:45 am, fatwallet...@ya hoo.com wrote:
    is the main function in python is exact compare to Java main method?
    >
    all execution start in main which may takes arguments?
    >
    Hi Fatwallet,
    May I have some of your money?

    Oh, sorry, the main function...

    The main function is *not* like that of Java, if Java is ike C in
    that execution starts in main().
    In Python, you can create a function called main and it behaves just
    like any other function.

    Stick that function in a file and the python interpreter will create a
    function object out of it, assigned to the name main.

    Now, while directly interpreting a python file, the interpreter sets
    the global name __name__ to the value '__main__'
    If the file is being interpreted due to it being referenced via an
    import statement, then __name__ is set to the name of the module being
    imported.

    You can therefore use the value of the __name__ variable to get a file
    to do different things when imported versus when directly run.
    Some people arrange for a function called main to be called when
    directly interpreted; other don't.

    Its a convention only.
    Others use the trick to call test functions when directly executed,
    when the file is normally imported as a module.

    and what is
    __name__
    __main__
    >
    use for in terms of Java?
    >
    With respect, (hehe), maybe you need to indicate that you've searched
    the Python documentation on __name__ and __main__?
    (Hah! I did that without saying RTFM. - Oh pooh! Fiddlesticks).

    - Paddy.

    Comment

    • Ben Finney

      #3
      Re: main

      fatwallet961@ya hoo.com writes:
      is the main function in python is exact compare to Java main method?
      all execution start in main which may takes arguments?
      There's no such thing in Python; a module is executed sequentially,
      with no particular regard to the names of any of the attributes.

      There is, though, a convention of writing a module that can be either
      imported or executed as a program, by testing inside the module
      whether the current module name is the magic string "__main__".

      === foo.py ===
      # This code is executed whether or not this module is the main module
      print "Module foo.py is running with name:", __name__

      if __name__ == '__main__':
      # This block is executed only if the module is the main program module
      print "Module foo.py is the main program"
      === foo.py ===

      === bar.py ===
      import foo

      print "Module bar.py is running with name:", __name__
      === bar.py ===

      =====
      $ python ./foo.py # Run foo.py as a program
      Module foo.py is running with name: __main__
      Module foo.py is the main program

      $ python ./bar.py # Run bar.py as a program, which imports foo.py as a module
      Module foo.py is running with name: foo
      Module bar.py is running with name: __main__
      =====

      That allows the following idiom:
      if __name__ == "__main__":
      sys.exit( main(sys.argv) )
      All the rest of the code is executed whether or not the program is the
      main module; but right at the end, after defining all the attributes
      and functions and classes etc., this test says *if* this module is the
      main program, then *also* execute the "main" function (and then exit
      Python with the return value from that function).

      The benefit of this is that this module, designed to be run as a
      program, is *also* designed to be imported by other programs so that
      its functions etc. can be used as required, *without* necessarily
      running the main function.

      --
      \ "If I haven't seen as far as others, it is because giants were |
      `\ standing on my shoulders." -- Hal Abelson |
      _o__) |
      Ben Finney

      Comment

      • Gabriel Genellina

        #4
        Re: main

        En Sat, 03 Feb 2007 02:37:11 -0300, Paddy <paddy3118@nets cape.net>
        escribió:
        >and what is
        >__name__
        >__main__
        >>
        >use for in terms of Java?
        >>
        >
        With respect, (hehe), maybe you need to indicate that you've searched
        the Python documentation on __name__ and __main__?
        (Hah! I did that without saying RTFM. - Oh pooh! Fiddlesticks).
        Have you acually tried to do the search? The Python tutorial doesn't
        menction that at all. And no one should expect that a beginner would have
        to read section 26.3 on the Language Reference (__main__ -- Top-level
        script environment) just to know what's that stuff about __name__ and
        "__main__". ..

        --
        Gabriel Genellina

        Comment

        • Paddy

          #5
          Re: main

          On Feb 3, 8:51 am, "Gabriel Genellina" <gagsl...@yahoo .com.arwrote:
          En Sat, 03 Feb 2007 02:37:11 -0300, Paddy <paddy3...@nets cape.net>
          escribió:
          >
          and what is
          __name__
          __main__
          >
          use for in terms of Java?
          >
          With respect, (hehe), maybe you need to indicate that you've searched
          the Python documentation on __name__ and __main__?
          (Hah! I did that without saying RTFM. - Oh pooh! Fiddlesticks).
          >
          Have you acually tried to do the search? The Python tutorial doesn't
          menction that at all. And no one should expect that a beginner would have
          to read section 26.3 on the Language Reference (__main__ -- Top-level
          script environment) just to know what's that stuff about __name__ and
          "__main__". ..
          >
          --
          Gabriel Genellina
          Good point.
          Googling for :
          tutorial "if __name__ = '__main__'"

          +__name__+%3D+% 27__main__%27%2 2&btnG=Search&m eta=
          Gives this excellent page by the effbot:


          In fact, fatwallet should add its index page to his bookmarks:


          Thanks Gabriel,
          - Paddy.

          Comment

          • Steven Bethard

            #6
            [OT] main

            fatwallet961@ya hoo.com wrote:
            def main(argv):
            try:
            optlist, args = getopt.getopt(a rgv[1:], 'hvo:D:', ['help',
            'verbose'])
            except getopt.GetoptEr ror, msg:
            sys.stderr.writ e("preprocess : error: %s" % msg)
            sys.stderr.writ e("See 'preprocess --help'.\n")
            return 1
            outfile = sys.stdout
            defines = {}
            for opt, optarg in optlist:
            if opt in ('-h', '--help'):
            sys.stdout.writ e(__doc__)
            return 0
            elif opt in ('-v', '--verbose'):
            log.setLevel(lo gging.DEBUG)
            elif opt == '-o':
            outfile = optarg
            elif opt == '-D':
            if optarg.find('=' ) != -1:
            var, val = optarg.split('= ', 1)
            try:
            val = eval(val, {}, {})
            except:
            pass
            else:
            var, val = optarg, None
            defines[var] = val
            >
            if len(args) != 1:
            sys.stderr.writ e("preprocess : error: incorrect number of "\
            "arguments: argv=%r\n" % argv)
            return 1
            else:
            infile = args[0]
            >
            try:
            preprocess(infi le, outfile, defines)
            except PreprocessError , ex:
            sys.stderr.writ e("preprocess : error: %s\n" % str(ex))
            This is offtopic, but I suggest looking into using optparse_ or
            argparse_ instead of getopt. This would simplify your code to something
            like::

            parser = argparse.Argume ntParser(descri ption='Preproce ss a file.')
            parser.add_argu ment('infile', default=sys.std in,
            type=argparse.F ileType('r'))
            parser.add_argu ment('-v', '--verbose', action='store_t rue')
            parser.add_argu ment('-o', dest='outfile', default=sys.std out,
            type=argparse.F ileType('w'))
            parser.add_argu ment('-D', dest='defines', action='append' )
            args = parser.parse_ar gs()

            if args.verbose is not None:
            log.setLevel(lo gging.DEBUG)

            defines = {}
            for define in args.define:
            var, sep, val = define.partitio n('=')
            defines[var] = val or None

            try:
            preprocess(args .infile, args.outfile, defines)
            except PreprocessError , ex:
            sys.stderr.writ e("preprocess : error: %s\n" % str(ex))

            Additionally, if you include your help messages using the help= argument
            to add_argument(), your usage message will be generated automatically.

            ... _optparse: http://docs.python.org/lib/module-optparse.html
            ... _argparse: http://argparse.python-hosting.com/

            STeVe

            Comment

            • Paddy

              #7
              Re: main

              On Feb 3, 10:53 pm, Dennis Lee Bieber <wlfr...@ix.net com.comwrote:
              On Sat, 03 Feb 2007 05:51:56 -0300, "Gabriel Genellina"
              <gagsl...@yahoo .com.ardeclaime d the following in comp.lang.pytho n:
              >
              menction that at all. And no one should expect that a beginner would have
              to read section 26.3 on the Language Reference (__main__ -- Top-level
              script environment) just to know what's that stuff about __name__ and
              "__main__". ..
              >
              OTOH: a true beginner, working out of the tutorial, is unlikely to
              be writing anything that really needs to know about this feature. For
              the most part, all this feature does is allow one to write safely
              importable modules (ie; modules that only define constants, classes, and
              functions when imported) that can also be used as stand-alone programs
              (often done to add test capability).
              Maybe, but viewing their profile of past posts on Google I got the
              feeling that fatwallet could be trying to understand existing code
              soehow.

              - Pad.

              Comment

              Working...