473,386 Members | 1,819 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

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(infile, outfile=sys.stdout, defines={})

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

# #if defined('FAV_COLOR') 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.__init__(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.getLogger("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':lambda v: v in defines}, defines)
except Exception, ex:
raise PreprocessError(str(ex), defines['__FILE__'],
defines['__LINE__'])
log.debug("evaluate %r -%s (defines=%r)", expr, rv, defines)
return rv

#---- module API

def preprocess(infile, outfile=sys.stdout, defines={}):
"""Preprocess 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("preprocess(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("defaulting 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|ifndef)\s+(?P<expr>.*?)' ,
'#\s*(?P<op>else|endif)',
'#\s*(?P<op>error)\s+(?P<error>.*?)',
'#\s*(?P<op>define)\s+(?P<var>[^\s]*?)(\s+(?P<val>.+?))?',
'#\s*(?P<op>undef)\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.StringTypes:
if os.path.exists(outfile):
os.chmod(outfile, 0777)
os.remove(outfile)
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(line)
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("var", "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("var")
try:
del defines[var]
except KeyError:
pass
elif op in ("if", "ifdef", "ifndef"):
if op == "if":
expr = match.group("expr")
elif op == "ifdef":
expr = "defined('%s')" % match.group("expr")
elif op == "ifndef":
expr = "not defined('%s')" % match.group("expr")
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("expr")
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("error")
raise PreprocessError("#error: "+error,
defines['__FILE__'],
defines['__LINE__'], line)
log.debug("states: %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("superfluous #endif before this
line",
defines['__FILE__'],
defines['__LINE__'])
if len(states) 1:
raise PreprocessError("unterminated #if block",
defines['__FILE__'],
defines['__LINE__'])
elif len(states) < 1:
raise PreprocessError("superfluous #endif on or before this
line",
defines['__FILE__'],
defines['__LINE__'])

if fout != outfile:
fout.close()
#---- mainline

def main(argv):
try:
optlist, args = getopt.getopt(argv[1:], 'hvo:D:', ['help',
'verbose'])
except getopt.GetoptError, msg:
sys.stderr.write("preprocess: error: %s" % msg)
sys.stderr.write("See 'preprocess --help'.\n")
return 1
outfile = sys.stdout
defines = {}
for opt, optarg in optlist:
if opt in ('-h', '--help'):
sys.stdout.write(__doc__)
return 0
elif opt in ('-v', '--verbose'):
log.setLevel(logging.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.write("preprocess: error: incorrect number of "\
"arguments: argv=%r\n" % argv)
return 1
else:
infile = args[0]

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

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

Feb 3 '07 #1
6 3794
On Feb 3, 4:45 am, fatwallet...@yahoo.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.

Feb 3 '07 #2
fa**********@yahoo.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

Feb 3 '07 #3
En Sat, 03 Feb 2007 02:37:11 -0300, Paddy <pa*******@netscape.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

Feb 3 '07 #4
On Feb 3, 8:51 am, "Gabriel Genellina" <gagsl...@yahoo.com.arwrote:
En Sat, 03 Feb 2007 02:37:11 -0300, Paddy <paddy3...@netscape.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__'"
http://www.google.co.uk/search?hl=en...tutorial+%22if
+__name__+%3D+%27__main__%27%22&btnG=Search&meta=
Gives this excellent page by the effbot:
http://effbot.org/pyfaq/tutor-what-i...e-main-for.htm

In fact, fatwallet should add its index page to his bookmarks:
http://effbot.org/pyfaq/

Thanks Gabriel,
- Paddy.

Feb 3 '07 #5
fa**********@yahoo.com wrote:
def main(argv):
try:
optlist, args = getopt.getopt(argv[1:], 'hvo:D:', ['help',
'verbose'])
except getopt.GetoptError, msg:
sys.stderr.write("preprocess: error: %s" % msg)
sys.stderr.write("See 'preprocess --help'.\n")
return 1
outfile = sys.stdout
defines = {}
for opt, optarg in optlist:
if opt in ('-h', '--help'):
sys.stdout.write(__doc__)
return 0
elif opt in ('-v', '--verbose'):
log.setLevel(logging.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.write("preprocess: error: incorrect number of "\
"arguments: argv=%r\n" % argv)
return 1
else:
infile = args[0]

try:
preprocess(infile, outfile, defines)
except PreprocessError, ex:
sys.stderr.write("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.ArgumentParser(description='Preprocess a file.')
parser.add_argument('infile', default=sys.stdin,
type=argparse.FileType('r'))
parser.add_argument('-v', '--verbose', action='store_true')
parser.add_argument('-o', dest='outfile', default=sys.stdout,
type=argparse.FileType('w'))
parser.add_argument('-D', dest='defines', action='append')
args = parser.parse_args()

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

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

try:
preprocess(args.infile, args.outfile, defines)
except PreprocessError, ex:
sys.stderr.write("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
Feb 4 '07 #6
On Feb 3, 10:53 pm, Dennis Lee Bieber <wlfr...@ix.netcom.comwrote:
On Sat, 03 Feb 2007 05:51:56 -0300, "Gabriel Genellina"
<gagsl...@yahoo.com.ardeclaimed the following in comp.lang.python:
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.

Feb 4 '07 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

192
by: Kwan Ting | last post by:
The_Sage, I see you've gotten yourself a twin asking for program in comp.lang.c++ . http://groups.google.co.uk/groups?hl=en&lr=&ie=UTF-8&oe=UTF-8&th=45cd1b289c71c33c&rnum=1 If you the oh so mighty...
45
by: Steven T. Hatton | last post by:
This is a purely *hypothetical* question. That means, it's /pretend/, CP. ;-) If you were forced at gunpoint to put all your code in classes, rather than in namespace scope (obviously classes...
15
by: Fred Zwarts | last post by:
In C++ execution of a program starts already before execution of main(). The initialization of static variables defined outside the scope of main is performed first. I could imagine a program where...
75
by: Beni | last post by:
I have been programming in C for about a year now. It sounds silly, but I never took the time to question why a C(or C++ or Java) program execution begins only at the main(). Is it a convention or...
5
by: Seong-Kook Shin | last post by:
Hi, I'm reading Steve's "C Programming FAQs" in book version, and have two question regarding to Q11.16 ... Also, a `return' from `main' cannot be expected to work if data local to main might be...
13
by: Sokar | last post by:
I have my main function set up as int main(int argv, char *argv) so taht i can read in a variable which is passed to the program on the command line. The problem is that main calls other...
16
by: Geoff Jones | last post by:
Hi What is the closest equivalent to Main in a VB.Net form? Geoff
2
by: psuaudi | last post by:
I have a main query that I would like to call two different subqueries. In MS Access, I usually just save the two subqueries as separate queries which are then called by a third separate and main...
28
by: ravi | last post by:
Hello everybody, I am writing a small application which does some work before the user main function starts execution. I am trying to #define the main function. But the problem is that,
11
by: aarklon | last post by:
Hi all, I have heard many discussions among my colleagues that main is a user defined function or not. arguments in favour:- 1) if it is built in function it must be defined in some header...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.