Python не закрывать консоль при ошибке

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 "PathTo Your Script"
Pythonbinpython.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:WINDOWSsystem32cmd.exe /K [existing command]

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

/K command - Executes the specified command and continues running.

I’m making a application in python from Windows. When I run it in the console, it stops, shows an error, and closes. I can’t see the error becase its too fast, and I can’t read it. I’m editing the code with IDLE (the program that came with python when I instaled it), and when I run it with the python shell, there are no errors. I would run it from IDLE, but when I use the console, it has more features.

I don’t know why this is happening. I need your help.

asked Aug 9, 2012 at 3:52

user1586464's user avatar

Run the program from an already-open terminal. Open a command prompt and type:

python myscript.py

For that to work you need the python executable in your path. Just check on how to edit environment variables on windows, and add C:PYTHON26 (or whatever directory you installed python to).When the program ends, it’ll drop you back to the CMD windows prompt instead of closing the window.Add code to wait at the end of your script. Adding …

raw_input()

… at the end of the script makes it wait for the ENTER key. That method is annoying because you have to modify the script, and have to remember removing it when you’re done.

answered Aug 9, 2012 at 3:56

Brian Carpio's user avatar

Brian CarpioBrian Carpio

4833 gold badges9 silver badges15 bronze badges

0

Run your program from a Windows command prompt. That will not automatically close when the program finishes.

If you run your program by double-clicking on the .py file icon, then Windows will close the window when your program finishes (whether it was successful or not).

answered Aug 9, 2012 at 3:55

Greg Hewgill's user avatar

Greg HewgillGreg Hewgill

944k182 gold badges1141 silver badges1280 bronze badges

0

Create a text file in the program directory i.e. wherever your script is located. Change the extension to .bat for example text.bat. Then edit the text file and write:

python main.exe
pause

Now you can run the program without typing into the command console by double clicking the bat file, and the console window will not close.

answered Nov 29, 2014 at 19:22

user4261180's user avatar

user4261180user4261180

1412 gold badges3 silver badges11 bronze badges

Ну раз уж начали улучшать код)

p = input('Введите ваш пол,буква (мж):n')

if p == 'м':
    answers = {
        'норм': 'Норм так норм,эт стандарт))',
        'плохо': '***,ну ты это,не расстраивайся,все еще наладится,выше нос)) ',
        'отлично': 'Так держать',
        'супер': 'Так держать',
    }
    print('Здарова мужик')
    k = input('Как дела то?) (норм,плохо,отлично,супер,свой вариант)n')
    print(answers[k] if k in answers else 'эхх,выпьем? =) ')
elif p == 'ж':
    answers = {
        'норм': 'Норм так норм,эт стандарт для девушки))',
        'плохо': '***,ну ты это,ъъъъъъ,не расстраивайся,все еще наладится,выше нос)) ',
        'отлично': 'Так держать, ъъъъъъ!',
        'супер': 'Так держать',
    }
    print('Приветствую вас девушка')
    k = input('Как дела, сударыня?) (норм,плохо,отлично,супер,свой вариант)n')
    print(answers[k] if k in answers else 'эхх,выпьем? =) а потом ъъъъъъ ')
else:
    print('Ты кто такой ***, ******')

input()

У вас может быть второй script, который импортирует/запускает ваш основной код. Этот script будет использовать все исключения и распечатать трассировку (затем дождаться ввода пользователя до окончания)

Предполагая, что ваш код структурирован с помощью if __name__ == "__main__": main() idiom..

def myfunction():
    pass

class Myclass():
    pass

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

if __name__ == "__main__":
    main()

.. и файл называется «myscriptname.py» (очевидно, что его можно изменить), будет работать

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()

(Обратите внимание, что raw_input() был заменен на input() в Python 3)

Если у вас нет функции main(), вы должны использовать оператор import в блоке try::

try:
    import myscriptname
except [...]

Лучшее решение, которое не требует дополнительных сценариев-оболочек, заключается в том, чтобы запустить script либо из IDLE, либо из командной строки.

В Windows откройте «Пуск» > «Выполнить», введите cmd и введите. Затем введите что-то вроде..

cd "PathTo Your Script"
Pythonbinpython.exe myscriptname.py

(Если вы установили Python в C:Python)

В Linux/Mac OS X это немного проще, вы просто запустите cd /home/your/script/, затем python myscriptname.py

Самый простой способ — использовать IDLE, запустить IDLE, открыть script и нажать кнопку запуска (F5 или Ctrl+F5, я думаю). Когда script завершается, окно не будет закрываться автоматически, поэтому вы можете увидеть любые ошибки

Кроме того, как предложил Крис Торнхилл, в Windows вы можете создать ярлык для своего script, а в нем Properties префикс цели с помощью

C:WINDOWSsystem32cmd.exe /K [existing command]

Из http://www.computerhope.com/cmd.htm:

/K command - Executes the specified command and continues running.

Как сделать чтобы консоль python не закрывалась

При работе с программами на языке Python иногда возникает ситуация, когда консоль закрывается сразу после выполнения кода. В этой статье мы рассмотрим способы, как предотвратить закрытие консоли Python.

1. Использование input()

Добавьте в конец своего кода функцию input(), которая позволяет приостановить выполнение программы и ждать ввода пользователя. Когда пользователь нажимает клавишу Enter, программа продолжает выполнение и заканчивает работу.

print("Привет, мир!")
input("Нажмите Enter, чтобы закрыть консоль...")

2. Запуск скрипта из командной строки

Запустите свой скрипт Python из командной строки (терминала) с использованием интерпретатора Python, а не двойным кликом по файлу. Это позволит сохранить окно консоли открытым после выполнения скрипта. Введите следующую команду в командной строке:

python ваш_скрипт.py

3. Использование IDE

Работайте с кодом в интегрированной среде разработки (IDE), такой как PyCharm, Visual Studio Code или других. В таких средах выполнение кода обычно происходит во встроенной консоли, которая остается открытой после завершения программы.

4. Использование модуля os

Импортируйте модуль os и используйте функцию os.system('pause') для приостановки выполнения программы. Обратите внимание, что этот метод работает только на Windows.

import os

print("Привет, мир!")
os.system('pause')

  • Python try except получить текст ошибки
  • Python логирование всех ошибок
  • Pycharm ошибка при установке библиотеки
  • Python try except печать ошибки
  • Python код ошибки 2503