How to write the main function python

Each programmer in the process of learning to program in, certainly no less written main () function, Python programmer is no exception. This article is to share the father of Python Guido van Rossum function recommended wording, can greatly improve the flexibility of this function.
In general, Python programmers probably write main () function:
"" "Module docstring.
This AS A Long Usage Serves as mentioned in the Message.
" ""
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 ()
Guido admits that main () function is similar to the structure prior to write their own, but wrote flexibility is not high enough, when complex command line options particularly the need to resolve. To this end, he put forward some suggestions to you.
Add the optional parameter argv
First, modify the main () function, it takes an optional parameter argv, support call this function in the interactive shell:
DEF main (argv = None):
IF IS None argv:
argv = SYS. argv

etc., replacing sys.argv with argv in the getopt() call.

In doing so, we can provide a value for argv dynamically, so write it more flexible than the following:
DEF main (argv = sys.argv):

etc.

This is because when you call the function, the value of sys.argv may vary; Optional Default parameters are defined in the main () function, the calculation has been good.
But now sys.exit () function call causes a problem: When the main () function call sys.exit (), will launch an interactive interpreter! The solution is to let the main () function's return value indicates the exit status (exit status). Accordingly, the rearmost line of code this becomes:
IF name == " main ":
the sys.exit (main ())
and, main () function in sys.exit (n) call all become return n .
Define a Usage () Exception
further improvement, is to define a Usage () anomalies, may be main () function to capture the last except clause exception:
Import SYS
Import the getopt
class the Usage (Exception):
DEF the init (Self, MSG):
self.msg MSG =
DEF main (the argv = None):
IF the argv None IS:
the argv = the sys.argv
the try:
the try:
the opts, args = getopt.getopt (the argv [. 1:], "H", [ " Help "])
the 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 ())
so that main () function is only one exit point (exit), this approach is better than the previous two exit points. Moreover, it is also reconstructed parameter parsing easier: AxiTrader rebate www.kaifx.cn/broker/axitrader.html, caused little problem in Usage of auxiliary function, but the use of return 2 but requires careful handling problems returned values passed .
== python in the name ' main ' role in
the classic English explanation: Make a script both importable and executable
Chinese explanation: the script can be called directly import and can also run
1, run directly

cat test_fun.py

def fun():
print(name)
print('this is fun')
if name == 'main':
fun()
print('this is main')
python test_fun.py
main
this is fun
this is main
2、被调用import

test_fun Import
test_fun.fun ()
test_fun
the this IS Fun
when introducing call: output is not displayed here "main", that is the module name = 'main' following code is not performed, main function is not performed.
This feature is also a useful: debug code, we add some debugging code "if name == 'main'", we can let the call when the external module does not perform our debugging code, but if we want to troubleshoot when the issue of direct implementation of the module file, debug code to run properly!
 python is an interpreted scripting language, and C / C ++ language different, C / C ++ program, the program execution python sequence from the beginning to the end of the main function begins execution. To summarize the main function of the python in effect: Let the module (function) can perform their own separate (debugging), equivalent to call other functions constructed entrance, which is similar to C / C ++ function inside the mian.
On the one hand: We want their execution (debug) alone
Here we look at the actual debugging (assuming that this file is test.py): #
test.py
Print ( 'the Hello World!')
DEF aaa ():
Print ( 'the this IS the Message AAA function from ')
DEF main ():
Print (' IS Message from the this main function ')
IF name ==' main ':
main ()
Print ( 'now name IS% S'% name )
execute python test.py output:
! the Hello World
the this IS the Message from main function
now name IS main
Here we see that we define aaa function is not executed, and the main function inside the content is executed, indicating IF name == ' main ': this statement is determined by performing the determination condition in the main (); 
on the other hand: the import function commands can be used inside the other .py files, we test.py modules (function) into call.py, and is noted test.py call.py placed in the same folder;
# call.py
from Test import AAA
AAA ()
Print ( 'now name iS S% '% name )
performed python call.py output:
! the Hello World
the this Message from AAA IS function
now name ISmain
so when we wrote the .py file, you want to test the function inside, and thus construct a main function entry can call the function test write their own friends ~

Guess you like

Origin blog.51cto.com/14511863/2437797