0

Feeling really stupid right now. I opened a python file in my Windows console and the file raised an error (such as TypeError, AttributeError, etc.) and the console won't work anymore so I have to close it and open a new window everytime I get an error. There should be a shortcut or something to exit but Ctrl+C doesn't work. I have Windows 10 and Python 3.6.

When I run my file in the console happens this:

C:\Users\...path...>python my_file.py

Traceback (most recent call last):
  File "C:\Users\...path...\my_file.py", line 74, 
  ...stuff...
AttributeError: my error

And after this I can't do anything. If someone could help.

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152

2 Answers2

1

On an unhandled exception, a Python program normally quits, and you get the console prompt back. If yours doesn't, it means that it hangs instead.

If Ctrl-C doesn't work, you can force-kill a Windows console program with Ctrl-Break.

But you really should find out why it hangs, as it's not normal. My guess is you're swallowing all exceptions somewhere, e.g. with an unqualified except: which is strongly discouraged exactly for this reason.

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152
  • I have no `except` in my program, I am using PyQt5 with a GUI so the problem could be there, thanks!! I don't know which key is break, could you clarify? – Antonia Cobo Jun 10 '18 at 15:59
  • 1
    Ctrl+Break doesn't forcibly kill a console program. It sends a `CTRL_BREAK_EVENT` by injecting a thread in the target process that runs `CtrlRoutine(CTRL_BREAK_EVENT)`, in which `CtrlRoutine` is an undocumented kernel32.dll export (e.g. try `ctypes.WinDLL('kernel32').CtrlRoutine(1)`, or 0 for Ctrl+C). The default handler, if called, exits via `ExitProcess`, in which case at least DLL cleanup code still runs. You can install a custom handler to exit gracefully via Ctrl+Break. The CRT's control handler maps this to `SIGBREAK`, which can be assigned to a Python function using the `signal` module. – Eryk Sun Jun 12 '18 at 09:30
  • @eryksun Gee, thanks for the info! Anyway, the important thing is, Python doesn't catch it by default and makes it disproportionally hard to catch it otherwise, so this will work almost always. While Ctrl-C won't if there's so much as the dreaded `except:`. – ivan_pozdeev Jun 12 '18 at 11:46
  • Handling Ctrl+Break isn't hard. Set a handler function via, e.g., `signal.signal(signal.SIGBREAK, sigbreak_handler)`. The handler should try to exit gracefully but fall back on a hard exit via `os._exit`. – Eryk Sun Jun 12 '18 at 12:11
0

May be because of bug/error your program become freeze. Please try to use exception handling. An example :

try:
    your_codes()
except Exception as ex:
    print(ex)

This is just an example of exception handling. You can do it in much better (but complicated!) approach. You can read this doc.

Taohidul Islam
  • 5,246
  • 3
  • 26
  • 39