How to terminate a Python script

前端 未结 10 1073
予麋鹿
予麋鹿 2020-11-22 04:34

I am aware of the die() command in PHP which exits a script early.

How can I do this in Python?

10条回答
  •  逝去的感伤
    2020-11-22 04:58

    I'm a total novice but surely this is cleaner and more controlled

    def main():
        try:
            Answer = 1/0
            print  Answer
        except:
            print 'Program terminated'
            return
        print 'You wont see this'
    
    if __name__ == '__main__': 
        main()
    

    ...

    Program terminated

    than

    import sys
    def main():
        try:
            Answer = 1/0
            print  Answer
        except:
            print 'Program terminated'
            sys.exit()
        print 'You wont see this'
    
    if __name__ == '__main__': 
        main()
    

    ...

    Program terminated Traceback (most recent call last): File "Z:\Directory\testdieprogram.py", line 12, in main() File "Z:\Directory\testdieprogram.py", line 8, in main sys.exit() SystemExit

    Edit

    The point being that the program ends smoothly and peacefully, rather than "I'VE STOPPED !!!!"

提交回复
热议问题