good idea to modify Python to accept continue statement in interactive mode? - python

as an alternative to using pdb, I would have a use for the Python continue statement in interactive mode, after control-C during a script invocation with python -i. that way, say at a raw_input('continue->') prompt in my script, I could break out, inspect/modify things, and go right back to the raw_input prompt (or whatever code caused an exception) with a continue command. the break command outside of a loop could also be repurposed for symmetry, but I'd have less use for that. before submitting a PEP for this, I'd like some feedback from the Python community.
it might be possible to do something similar just using a PYTHONSTARTUP script and the inspect module, but if so I haven't figured it out yet.

ctrl-C raised a KeyboardInterrupt exception in your script. Since you didn't catch that exception, the program terminated. Only then the interactive prompt appears.
You can't continue because your program is already over. The fact that you pressed Ctrl-C just raised an exception, the program didn't pause at that exact place. It continued execution, up to the last line, and finished.
There's no way to know where you want to continue to. For that you need a real debugger.

Related

How to halt a Python script - only if it is being debugged

A similar question
When developing some Windows desktop stuff in Delphi, I had a habit of inserting
asm(int 3);.
If a debugger is running, that acts like a breakpoint. If no debugger is running, it does nothing (NOOP).
I would like to do something similar for my Python scripts. Is there some Python function like HaltDebugger()? Cross platform, of course.
[Update] I am looking for something that will work with PyCharm
This is the most portable solution. A more difficult one is sketched below for PyCharm.
Kind of depends on the debugger, but if you use pdb (which would be cross platform), the docs state:
The typical usage to break into the debugger from a running program is
to insert
import pdb; pdb.set_trace()
you want this to be conditional, so you can paste at each breakpoint:
try: pdb.set_trace()
except NameError: pass
and when you want to debug just import pdb at the top. If it must be one line you cannot use duck typing. Instead:
if 'pdb' in globals(): pdb.set_trace()
PyCharm only
Assuming you insist on not marking debugging lines with the mouse this might work:
Using exception breakpoints:
PyCharm provides exception breakpoints for Python, Django, and
JavaScript.
Exception breakpoints are triggered when the specified exception is
thrown. Unlike the line breakpoints, which require specific source
references, exception breakpoints apply globally to the exception
condition, rather than to a particular code reference.
Depending on the type of processing an exception, the debugging can
break when a process terminates with an exception, or as soon as an
exception occurs.
You could:
Create a custom exception in your project, DebugException
Set the exception breakpoint as per the link above. Make sure it is set to trigger immediately, not when program exits.
Finally,
paste
try: raise DebugException()
Exception: pass
wherever you want to break. This seems like a lot of trouble to not double click with your mouse to mark a breakpoint.

Automatically restart a Python program if it's killed

I run a Python Discord bot. I import some modules and have some events. Now and then, it seems like the script gets killed for some unknown reason. Maybe because of an error/exception or some connection issue maybe? I'm no Python expert but I managed to get my bot working pretty well, I just don't exactly understand how it works under the hood (since the program does nothing besides waiting for events). Either way, I'd like it to restart automatically after it stops.
I use Windows 10 and just start my program either by double-clicking on it or through pythonw.exe if I don't want the window. What would be the best approach to verify if my program is still running (it doesn't have to be instant, the verification could be done every X minutes)? I thought of using a batch file or another Python script but I have no idea how to do such thing.
Thanks for your help.
You can write another python code (B) to call your original python code (A) using Popen from subprocess. In python code (B), ask the program to wait for your python code (A). If 'A' exits with an error code, recall it from B.
I provide an example for python_code_B.py
import subprocess
filename = 'my_python_code_A.py'
while True:
"""However, you should be careful with the '.wait()'"""
p = subprocess.Popen('python '+filename, shell=True).wait()
"""#if your there is an error from running 'my_python_code_A.py',
the while loop will be repeated,
otherwise the program will break from the loop"""
if p != 0:
continue
else:
break
This will generally work well on Unix / Windows systems. Tested on Win7/10 with latest code update.
Also, please run python_code_B.py from a 'real terminal' which means running from a command prompt or terminal, and not in IDLE.
for problem you stated i prefer to use python subprocess call to rerun python script or use try blocks.
This might be helpful to you.
check this sample try block code:
try:
import xyz # consider it is not exist or any error code
except:
pass # go to next line of code to execute

How to retry before an exception with Eclipse/PyDev

I am using Eclipse + PyDev, although I can break on exception using PyDev->Manage Exception Breakpoints, I am unable to continue the execution after the exception.
What I would like to be able to do is to set the next statement before the exception so I can run a few commands in the console window and continue execution. If I use Eclipse -> Run -> Set Next Statement before the exception, the editor will show the next statement being where I set it but then when resuming the execution, the program will be terminated.
Can this be done ?
Unfortunately no, this is a Python restriction on setting the next line to be executed: it can't set the next statement after an exception is thrown (it can't even go to a different block -- i.e.: if you're inside a try..except, you can't set the next statement to be out of that block).
You could in theory take a look at Python itself as it's open source and see how it handles that and make it more generic to handle your situation, but apart from that, what you want is not doable.

Python exit from all function and stop the execution

I'm trying to develop a script that will connect to our switch and do some tasks.
In this script I have a main function that calls a second function. In the second function I pass a list of switches that Python will start to connect one by one.
The second function will call a third function. In the third function the script makes some tests. If one of these tests fail I want to close the entire script.
The problem is that I tried to put return, exit, raise System, os.exit but what happens is that the script doesn't stop, it just jumps to another switch and goes on.
Anyone knows how can I close my entire script from a function?
Best regards.
You can use
import sys
sys.exit()
or
raise SystemExit()
The parameters can be used to pass messages. If you are also dealing with loops, break also works really well.
Try using sys.exit(). sys.exit() will raise a SystemExit exception and close the program.
Thanks for your reply.
I already tried use sys.exit, raise and others into the third funcion but nothing works. What I did, I put a return with stantement pass or fail. On the secund function I test the return and if fail the script execute sys.exit(). When I do this on the secund function the script stop like we want. Now it's working fine. Probably this is the worst way to do this but worked.
Best regards.

Python Debugging : Find where an exception is raised, go into debug mode?

Is there a command in the Python debugger (pdb) that says something like "run until the next exception is raised?"
Seems an obvious requirement but can't seem to find it.
Update : To be clear, my problem is an exception which is being caught and turned into an inadequate message in a log file. And I can't find where the exception is raised.
I figured that if I could go into trace mode and say "run until an exception is thrown" that would be the most straightforward way of finding it. I don't think post-mortem will work here.
Execute your script as follows:
python -m pdb myscript.py
Press c and Enter.
When an uncaught exception is raised you program will stop running and fall back to the pdb debug prompt.
Can you search the code in the failing script for the text of the message that is logged (I realize that this may be difficult if the string is generated in a complex way). If you can find the point where the message is generated/logged then you can set an appropriate break point to troubleshoot the problem.
Unfortunately, AFAIK Python pdb debugging does not offer the capability that is present in some other languages to say, for example, break when Exception is raised.

Categories

Resources