0

This question may have been asked a couple of times but I cannot seem to find it.

Basically I am just learning Python and I am on Windows, this means I double click the .py file and open it. This works great until an error appears, at which point Python calls exit and the window closes.

One way, of course, to get around this is to use the cmd program in Windows and run the Python program from there, however, is there a way to fix it so that my application doesn't bail out and close as soon as it hits an error if I open it from Windows Explorer?

while(True):
    try:
        number = input('Enter a number: ')

        if(is_int(number) is False):
            print('Please actually enter a number')
        if(number > 0):
            answer = input('Oh Noes you really want that?')
            if(answer == 'yes'):
                sys.exit(0);
    except KeyboardInterrupt:
        sys.exit(0)
    except Exception as e:

        input('')
Sammaye
  • 43,242
  • 7
  • 104
  • 146
  • The most common way is to let it wait for an input, then ignore the input and terminate the script. – Seçkin Savaşçı Mar 16 '14 at 12:32
  • @SeçkinSavaşçı well I am waiting for input, but I mean say it hits a `TypeError` and exits because of a fault in my applications coding – Sammaye Mar 16 '14 at 12:33
  • Can you add this example to the question body for clarification? – Seçkin Savaşçı Mar 16 '14 at 12:35
  • @SeçkinSavaşçı using what you just said I added the last except I was in the process of discovering how to print out the exception properly, edited – Sammaye Mar 16 '14 at 12:36
  • 1
    The "right" ways would be: (1) use `cmd` or (2) use IDE (e.g. IDLE, which is shipped with python for windows) – J0HN Mar 16 '14 at 12:38
  • @J0HN ah yeah I didn't know IDLE could run the module but it can thanks – Sammaye Mar 16 '14 at 12:38
  • @J0HN I completely agree with you. Current answers don't mention about the best practices, I suggest you to write an answer why it is better to use console or IDE. That will be most beneficial for future hitchhikers. – Seçkin Savaşçı Mar 16 '14 at 12:41
  • @SeçkinSavaşçı awesome thanks for your help, I got it working perfectly now, printing out in the exact same manner as the base interpreter does and halting for input – Sammaye Mar 16 '14 at 12:46

5 Answers5

2

In order to keep your program intact, e.g. to not introduce unwanted catch-em-all exception handling (aka pokemon handling) there are at least three options:

  1. Use any console terminal, e.g. built-in cmd or powershell or any third-party console apps out there.
  2. Use any IDE: pycharm, IDLE (python windows installer by default sets it up) or whatever you have capable of running python code.
  3. Use text editor plugins for running python code. At least notepad++ and sublime text are capable of doing so.

I would recommend starting with option 1 for starters, then slowly move to option 3 for small scripts and projects, and option two for larger ones.

Community
  • 1
  • 1
J0HN
  • 26,063
  • 5
  • 54
  • 85
  • Is it bad to use a catch all error handler like this? I am used to PHP so I am wondering if creating a global error handler like in PHP is wrong. – Sammaye Mar 16 '14 at 12:55
  • @Sammaye Well, take a look at the "Zen of Python"; and in my opinion, you will find the answer. – Seçkin Savaşçı Mar 16 '14 at 13:02
  • @Sammaye depends on what do you do in your exception handler and what's the purpose of your script. PHP is practically limited to dynamic web pages, while python is widely used in "desktop" applications: scripts, cronjobs, science software,etc. While it makes some sense to catch everthing in web to hide it from end user, it's not quite good idea to silence errors in "desktop" applications – J0HN Mar 16 '14 at 13:04
  • @SeçkinSavaşçı heh, yeah it does break a couple of the principles under the Zen code – Sammaye Mar 16 '14 at 13:06
  • @J0HN Ok kool, I think I am going to focus on keeping errors towards the functions and procedures in question atm – Sammaye Mar 16 '14 at 13:06
1

I you put an input function at the bottom of your script then it will hang there until you hit enter or close the command prompt. If you call an exit function put it immediately before the exit function is called. Otherwise place it at the bottom of the script.

Also I assume you have defined is_int already in your script?

stmfunk
  • 663
  • 5
  • 20
1

What would you think it should do?

Python is drawing the window you see, if python crashes, the windows is going away.

You can run it trough cmd, or within an IDE. (like IDLE, that has some problem though when it comes to GUI)

Otherwise, add something like this at the end of the file

try:
     run() 
except Exception as inst:
     print type(inst), inst.args
     #it prints the exception
     print sys.exc_traceback.tb_lineno 
     #if you want the line number where the error occurred in the source code
     raw_input()

inst is the exception instance, you can see the type and the list of arguments. Then with the sys module you can also see the line where the error occurred in the code.

This way every error will be handled and displayed before closing

Is this the right way?

No. You should really be using ad IDE (like Eclipse with PyDev or PyCharm).

Ant
  • 5,151
  • 2
  • 26
  • 43
  • But it doesn't give very good output, it gives me the machine readable output of the error – Sammaye Mar 16 '14 at 12:41
  • Thanks for the tip about the IDE, I actually use PyDev but since PDTs own debug tools are quite bad I never bothered with PyDevs but actually they do work quite well – Sammaye Mar 16 '14 at 18:28
0

After @SeçkinSavaşçı's extremely useful comment at the start:

The most common way is to let it wait for an input, then ignore the input and terminate the script.

Which took me a second to understand I went in search of how to do this, so first I saw to stop the script and used:

while(True):
    try:
        # Application code here
    except:
        input('')

Which worked really well to catch all errors, which unlike in PHP (which I have become comfortable with unfortunately) are all exceptions.

So the next part was to to tell me what error had occured and how to fix it, I needed a backtrace. It just so happens that the Python docs gave me the answer right here: http://docs.python.org/2/library/traceback.html#traceback-examples in an easy to see example:

exc_type, exc_value, exc_traceback = sys.exc_info()
print(traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout));

Add that above the input('') and I had my perfect error handling showing me everything I needed.

Thanks all,

Sammaye
  • 43,242
  • 7
  • 104
  • 146
0

Try import time and time.sleep(). Also, I recommend you to use IDLE or Geany. I've been using them and they work out well.