Мешайте Python закрыться на ошибке

Вам необходимо объединить ResourceDictionary с вашим App.xaml:


    
        
            
                
            
        
    

. Как только он попадет в область действия, вы можете ссылаться на любой ресурс, используя {DynamicResource key} или {StaticResource key}

[118 ] В чем разница между StaticResource и DynamicResource в WPF?

17
задан Shard 22 April 2009 в 23:31
поделиться

6 ответов

If you doing this on a Windows OS, you can prefix the target of your shortcut with:

C:\WINDOWS\system32\cmd.exe /K <command>

This will prevent the window from closing when the command exits.

16
ответ дан 30 November 2019 в 10:13
поделиться

Вы можете зарегистрировать обработчик исключений верхнего уровня, который поддерживает работу приложения при возникновении необработанного исключения:

def show_exception_and_exit(exc_type, exc_value, tb):
    import traceback
    traceback.print_exception(exc_type, exc_value, tb)
    raw_input("Press key to exit.")
    sys.exit(-1)

 import sys
 sys.excepthook = show_exception_and_exit

Это особенно полезно, если в обработчиках событий, вызываемых из C, возникают исключения. код, который часто не распространяет ошибки.

17
ответ дан 30 November 2019 в 10:13
поделиться
try:
    #do some stuff
    1/0 #stuff that generated the exception
except Exception as ex:
    print ex
    raw_input()
15
ответ дан 30 November 2019 в 10:13
поделиться

You could have a second script, which imports/runs your main code. This script would catch all exceptions, and print a traceback (then wait for user input before ending)

Assuming your code is structured using the if __name__ == "__main__": main() idiom..

def myfunction():
    pass

class Myclass():
    pass

def main():
    c = Myclass()
    myfunction(c)

if __name__ == "__main__":
    main()

..and the file is named "myscriptname.py" (obviously that can be changed), the following will work

from myscriptname import main as myscript_main

try:
    myscript_main()
except Exception, errormsg:
    print "Script errored!"
    print "Error message: %s" % errormsg
    print "Traceback:"
    import traceback
    traceback.print_exc()
    print "Press return to exit.."
    raw_input()

(Note that raw_input() has been replaced by input() in Python 3)

If you don't have a main() function, you would use put the import statement in the try: block:

try:
    import myscriptname
except [...]

A better solution, one that requires no extra wrapper-scripts, is to run the script either from IDLE, or the command line..

On Windows, go to Start > Run, enter cmd and enter. Then enter something like..

cd "\Path\To Your\ Script\"
\Python\bin\python.exe myscriptname.py

(If you installed Python into C:\Python\)

On Linux/Mac OS X it's a bit easier, you just run cd /home/your/script/ then python myscriptname.py

The easiest way would be to use IDLE, launch IDLE, open the script and click the run button (F5 or Ctrl+F5 I think). When the script exits, the window will not close automatically, so you can see any errors

Also, as Chris Thornhill suggested, on Windows, you can create a shortcut to your script, and in it's Properties prefix the target with..

C:\WINDOWS\system32\cmd.exe /K [existing command]

From http://www.computerhope.com/cmd.htm:

/K command - Executes the specified command and continues running.
7
ответ дан 30 November 2019 в 10:13
поделиться

Ваш вопрос не очень понятен, но я предполагаю, что интерпретатор python завершается (и, следовательно, окно вызывающей консоли закрывается), когда происходит исключение.

Вам необходимо изменить приложение python на поймать исключение и распечатать его, не выходя из интерпретатора. Один из способов сделать это - напечатать «нажмите клавишу ВВОД для выхода», а затем прочитать некоторые данные из окна консоли, фактически ожидая, пока пользователь нажмет клавишу «Ввод».

0
ответ дан 30 November 2019 в 10:13
поделиться

On UNIX systems (Windows has already been covered above...) you can change the interpreter argument to include the -i flag:

#!/usr/bin/python -i

From the man page:

-i

When a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command. It does not read the $PYTHONSTARTUP file. This can be useful to inspect global variables or a stack trace when a script raises an exception.

6
ответ дан 30 November 2019 в 10:13
поделиться
Другие вопросы по тегам:

Похожие вопросы: