简体   繁体   中英

How do I keep a console window open after my python program terminates to see any errors produced?

I am using python 3 on Win10 and running my code by opening a Command Prompt window and typing the file location. However, the window closes as soon as the program terminates, and before I can read any errors. Edit: This happens whether or not the program has errors. Thank you.

Solution 1:

I just saw your comment:

When I do that, I recieve the error 'python' is not recognized as an internal or external command, operable program or batch file

It looks like you haven't specified the path to the python executable: you need to add the python executable path to your Window's PATH variable. You can see how to do that here: Add Python to the PATH Environmental Variable ('python' is not recognized as an internal or external command)

Solution 2 :

You can use input("enter to exit") at the end of your python code to keep the program alive. It would exit once you press enter.

You could also surround your code in a try except statement and place thr input() in the except to prevent the program from exiting when there are errors, but like @Kevin mentioned in the comments, this would catch run time errors but not syntax errors.

Solution 3 :

You can write errors or anything information you want to a file such as log.txt for example, and then read that log file once the code finishes running eg how to write to a file in Python

FWIW, I have several Python versions on my Windows system, so I don't want to add any Python directories to my path permanently.

Code for each version is in a separate folder (eg 'py37'), with a subfolder for each project eg 'myProject'. In py37, there's a batch file called pyEnv.bat with this content:

@echo off
path=%path%;C:\Python37\;C:\Python37\Scripts\
cd.
cmd

In Windows explorer, I head over to the project folder I want to work in, click in the address bar and type ..\\pyEnv . That launches a DOS-box, in which I now can do python myproject.py . You can see print() output, errors, and so on.

You can up-arrow to try different modules, having typed them first.

Once you quit the DOS-box, your path is back to normal again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM