return与exit的区别

xit()是一个函数
,结束一个进程,它将删除进程使用的内存空间,同时把错误信息返回父进程,在父进程中wait系统调用将接受到此返回信息。


return返回函数值,是关键字

在main函数中我们通常使用return (0);这样的方式返回一个值。

  但这是限定在非void情况下的也就是void main()这样的形式。

  exit()通常是用在子程序中用来终结程序用的,使用后程序自动结束跳会操作系统。

  但在如果把exit用在main内的时候无论main是否定义成void返回的值都是有效的,并且exit不需要考虑类型,exit(1)等价于return (1)

exit(0);   //正常退出  
非0即是非正常退出
数字0,1,-1会被写入环境变量ERRORLEVEL,其它程序可以由此判断程序结束状态。  
一般0为正常推出,其它数字为异常,其对应的错误可以自己指定。

 

Python main() functions

I've written a few main() functions in my time. They usually have a structure roughly like this:

"""Module docstring.

This serves as a long usage 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()

I'm sure many people write similar main() functions. I've got a few suggestions that make main() a little more flexible, especially as option parsing becomes more complex.

First, we change main() to take an optional 'argv' argument, which allows us to call it from the interactive Python prompt:

def main(argv=None):
    if argv is None:
        argv = sys.argv
    # etc., replacing sys.argv with argv in the getopt() call.

Note that we fill in the default for argv dynamically. This is more flexible than writing

def main(argv=sys.argv):
    # etc.

because sys.argv might have been changed by the time the call is made; the default argument is calculated at the time the main() function is defined, for all times.

Now the sys.exit() calls are annoying: when main() calls sys.exit(), your interactive Python interpreter will exit! The remedy is to let main()'s return value specify the exit status. Thus, the code at the very end becomes

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

and the calls to sys.exit(n) inside main() all become return n.

Another refinement is to define a Usage() exception, which we catch in an except clause at the end of 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())

This gives the main() function a single exit point, which is preferable over multiple return 2 statements. This also makes it easier to refactor the argument parsing: raise Usage works just fine from inside a helper function, but return 2 would require careful passing on of the return values.

You might think that taking this to the extreme would move the try/except clause out of the main() function, into the code at the end of the module (if __name__ == "__main__": .... But that would mean that when you call main() interactively, you'd get a traceback for command line syntax errors, which isn't very helpful.

However, another generalization can be helpful: define another exception, perhaps called Error, which is treated just like Usage but returns 1. This can then be used for expected errors like failure to open necessary files, which are not command line syntax errors, but yet expected, and where again a traceback doesn't feel very friendly.

What's your favorite convention for writing main()?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值