Mars Lee
Mars Lee

Reputation: 1945

How to make Python executable pause when it raises an error?

So I know I can make Python executable using pyinstaller.

However, every time it raises an error, it will instantly end the program, so I can't find what is the error.

I know I probably can use time.sleep(30000) to stop it.

But if the code raises error before it meets time.sleep(30000), it will just shut down.

To sum up, how to make it keep not shutting down, so I can see where is the mistake?

Upvotes: 5

Views: 9547

Answers (5)

kindall
kindall

Reputation: 184320

Here's another way, using Python's exception hook:

import sys

def myexcepthook(type, value, traceback, oldhook=sys.excepthook):
    oldhook(type, value, traceback)
    raw_input("Press RETURN. ")    # use input() in Python 3.x

sys.excepthook = myexcepthook

The exception hook is called whenever Python wants to print an exception. In this case, we call the previously-installed exception hook (which prints the exception), then wait for the user to press Return.

Upvotes: 6

nneonneo
nneonneo

Reputation: 179592

From your description, it sounds like you are running a console program (i.e. a program with a visible console window).

If so, you have two options:

  1. Run it in a console window. This simply consists of running a command prompt or terminal emulator (which comes with your computer), cding into the directory containing the program, then running it by entering the program name. When the program quits (e.g. due to an error) the traceback will be printed out and you'll be returned to the prompt.
  2. You can add a try/except around your whole program that catches any errors and reports them. For example:

    try:
        main()
    except Exception:
        import traceback
        traceback.print_exc()
        raw_input("Program crashed; press Enter to exit")
    

Upvotes: 3

James Jithin
James Jithin

Reputation: 10555

If you are running the executable just by double clicking, try running it from console. For e.g. in Windows:

In cmd, run

cd executable_path myexecutable.exe

A better way would be to introduce logger so that other modules with logging implemented can write to files.

Also, you can put the code in try-except block:

try:
    #my_code_here
    print('Here is where the exception is')
except Exception as e:
    print('Unexpected error:' + str(e))

Upvotes: 4

Edward
Edward

Reputation: 2359

You can use try except like what Mars Lee said or you can do a

print("Test 1");

after a certain amount of lines.

Upvotes: -1

TigerhawkT3
TigerhawkT3

Reputation: 49330

Instead of just double-clicking the file, run it from the command line. A terminal window that your program automatically created will also be automatically closed when the program ends, but if you open a terminal yourself and run the program from the command line, it won't touch the open terminal and you can read the error.

Upvotes: 0

Related Questions