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('')
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:
Use any console terminal, e.g. built-in cmd or powershell or any third-party console apps out there.
Use any IDE: pycharm, IDLE (python windows installer by default sets it up) or whatever you have capable of running python code.
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.
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?
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).
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,
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.
Related
Edited* Solution: Remove "pause".
I'm running a python script which calls upon powershell to execute a line of code:
def download():
subprocess.call('C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe yt-dlp https://www.youtube.com/watch?v=jtjnnykvnh4;pause', shell=True)
download()
The problem was that after executing, it would output "Press Enter to continue..." This interrupts the program.*in my original example I forgot to include the ";pause" which is what turned out to be what was causing the interruption in the program, as kindly pointed out by the marked answer.
Below is the fixed line of code which does not prompt "press enter to continue" after running:
def download():
subprocess.call('C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe yt-dlp https://www.youtube.com/watch?v=jtjnnykvnh4;kill $pid', shell=True)
download()
Apologies for confusion caused by the original post. Thanks for the help.
PowerShell normally exits unless you specify -NoExit at the commandline. Even then it will not include the message you are seeing unless you add a pause at the end instead. Even so, I would expect your command to look more like
'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe & {yt-dlp https://www.youtube.com/watch?v=jtjnnykvnh4}'
My guess this has more to do with Python, though I have not encountered it before...have you tried executing the PowerShell line from another commandline (cmd on Windows or bash on Linux/Mac or another favourite) to verify that you get the same result independently of Python?
Another possibility is that it is the yt-dlp tool that you are using that has the pause effect (I am not familiar with the tool). Is it a PowerShell module? Or is it something that can be run on the commandline and you don't need PowerShell as a middleman anyway? Would it have a "silent" or "-q" argument, or another more relevant argument?
try:
some code here
except Exception as e:
print("error: ",e)
here if this python exe code produces an exception it immediately closes the exe terminal
how do I stop it from exiting the exe terminal so that I can understand what exception exactly occurred
also I cant run it in CMD I have to run the exe file only
also I cant use the press any key method
The terminal closes when the program terminates. When you catch the exception, you print your error message, and then the program terminate, so you don't really gain much from catching the exception; in fact, you even get less (you don't print the stack trace).
To get the stacktrace, look into traceback:
try:
foo = 123 / 0
except Exception as e:
traceback.print_exception(e)
Then you need to have the program wait a bit that you can actually see the stack trace and error you print. A simple way is to just wait for input:
try:
foo = 123 / 0
except Exception as e:
traceback.print_exception(e)
wait_for_it = input('Press enter to close the terminal window')
Or you could add a break point to have the Python debugger pdb come up. (It does at least on Mac OS when I run this code in a terminal, no idea about Windows.) See the above link for help on it, or type help at its prompt.
try:
foo = 123 / 0
except Exception as e:
breakpoint()
Speaking of terminal: if you just open a command prompt or bash terminal, you can just run your code with python3 myprog.py and that terminal does not automatically close, so that you can see the output without modifying the program. Depending on how you run your code and what module dependencies you have, this may need a bit more setup (like a virtual environment) but is probably worth it in the long run.
I like to paste hunks of code into an ipython window during development and debug. I also have a situation where I want to stop execution if a condition happens:
if condition:
<stop running>
Solutions like sys.exit() appear to exit all the way out of ipython back to a terminal prompt. Is there another way? At the moment I do this:
if condition:
fjklsd;
Which gives an error and returns to the ipython prompt, but is pretty ugly too.
You can raise this exception raise KeyboardInterrupt
I'm working on a python program that should wait for another program to update a .txt file, and when the file was updated my program should open it, get the command the other program just made, and then run something else. I'm quite new to python so a generic but well-explained solution would be great.
I've found How do I watch a file for changes? that leads to the solution here, but I can't quite understand how this works. The program could also be in other languages but it should trigger my python modules.
Here's the general idea of what I'm looking for.
sub GET_FILE_UPDATE:
try:
while change == False:
time.sleep(1)
else
if change == True
'open file and read command'
run.command()
except KeyboardInterrupt:
'stop program'
I Have a shell script which in turn runs a python script, I have to exit from the main shell script when an exception is caught in python. Can anyone suggest a way on how to achieve it.
In Python you can set the return value using sys.exit(). Typically when execution completed successfully you return 0, and if not then some non-zero number.
So something like this in your Python will work:
import sys
try:
....
except:
sys.exit(1)
And then, as others have said, you need to make sure your bash script catches the error by either checking the return value explicitly (using e.g. $?) or using set -e.