endolith
endolith

Reputation: 26785

How to prevent command line windows from closing after errors

In Windows, when a Python script exits, the Command Prompt window closes. If it exited from an error, it closes before you can read anything. I've been using this to hold the window open even on errors:

if __name__ == '__main__':
    try:
        main()
    except BaseException as e:
        print('Error:')
        print(e)
        raise
    finally:
        raw_input('(Press <Enter> to close)')

It works if main() calls sys.exit(), but doesn't work for things like syntax errors. Is there a better way?

Upvotes: 2

Views: 2774

Answers (2)

KurzedMetal
KurzedMetal

Reputation: 12946

I'm using a batch file with this code right now

@echo off
env\project_env\Scripts\python.exe -mpdb test.py
pause

env\project_env is a virtualenv directory with the libraries used by test.py

env\project_env\Scripts\python.exe is a python interpreter that makes the virtualenv magic to use the libraries installed in it.

-mpdb will open a debugger if the program terminates with an uncatched exception.

Upvotes: 3

NPE
NPE

Reputation: 500167

What you have will work in most scenarios (a thread calling os._exit() is one notable exception).

An alternative is to wrap the Python script in a batch file, and use the pause command after invoking the Python interpreter.

Upvotes: 4

Related Questions