How to keep a Python script output window open?

前端 未结 23 2564
挽巷
挽巷 2020-11-22 10:54

I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can an

23条回答
  •  渐次进展
    2020-11-22 11:05

    To keep your window open in case of exception (yet, while printing the exception)

    Python 2

    if __name__ == '__main__':
        try:
            ## your code, typically one function call
        except Exception:
            import sys
            print sys.exc_info()[0]
            import traceback
            print traceback.format_exc()
            print "Press Enter to continue ..." 
            raw_input() 
    

    To keep the window open in any case:

    if __name__ == '__main__':
        try:
            ## your code, typically one function call
        except Exception:
            import sys
            print sys.exc_info()[0]
            import traceback
            print traceback.format_exc()
        finally:
            print "Press Enter to continue ..." 
            raw_input()
    

    Python 3

    For Python3 you'll have to use input() in place of raw_input(), and of course adapt the print statements.

    if __name__ == '__main__':
        try:
            ## your code, typically one function call
        except BaseException:
            import sys
            print(sys.exc_info()[0])
            import traceback
            print(traceback.format_exc())
            print("Press Enter to continue ...")
            input() 
    

    To keep the window open in any case:

    if __name__ == '__main__':
        try:
            ## your code, typically one function call
    except BaseException:
        import sys
        print(sys.exc_info()[0])
        import traceback
        print(traceback.format_exc())
    finally:
        print("Press Enter to continue ...")
        input()
    

提交回复
热议问题