How to quit python script in gdb-python? - python-2.7

I am writing a python(v2.7) script in GDB(v7.5.1-0.7.29). I want to quit the python script when certain condition got false. But i do not want to quit GDB. I tried using sys.exit(), exit() and quit(), but in those case they also quit GDB. Is there any way to just quit the python script but not the gdb. Like ctrl + c command but i want this happend only when a certain condition got false.

CTRL+D does that
(gdb) pi
>>> [Press CTRL+D]
(gdb)

You have to raise an exception. Question is what exception to raise; whether you provide code to catch it and whether you want traceback to be printed or not.
If you don't mind traceback to be printed you can raise KeyboardInterrupt. But I presume you want graceful exit without traceback.
If you are writing code for class that integrates into GDB command then you can raise gdb.GdbError. It will be consumed by the code implementing command class and no traceback is printed.
If you are writing a script that is executed by sourcing it then you have to embed your whole script into try / except and catch exception you are raising. In fact, calling exit() also simply raises exception SystemExit, so you may write your script as:
try:
some code
if some_condition:
exit()
some more code
except SystemExit:
pass

Related

How can I prevent infinite loop in subprocess of python?

I am writing a python script that executes another program with bash command.
I am using subprocess.Popen() function for it. However in some conditions the external program gives me an error and tries to run same comment infinitely.
How can I catch that error and break Popen function.
Assume that program gives its error as an output.
You can use poll() or communicate() function for this. These methods return returncode once the process terminates. The return code is None as long as programme is running.
You can try using below code
from subprocess import Popen
process = Popen('bash your_script.sh')
while process.poll() is None:
print 'keep running'
process.terminate()

Python - Unexpected EOF while parsing

I am using REPL.it to run Python for my homework. When typing in and running this line of code:
# print "This will not run"
I get an unexpected EOF error:
Traceback (most recent call last):
File "python", line 1
# print "This will not run"
^
SyntaxError: unexpected EOF while parsing
This is an issue with REPL.it, not with Python. I am not sure what the internals of that interpreter are, but it appears that REPL.it will not allow a comment as the first line of code if there is no other code. To illustrate, try the following:
foo = 1
# print "This will not run"
The interpreter should spit out None instead of raising an error. It seems that it also works to have a comment on the first line and an empty line (or a line with code) as the second line, but running a file in this app that consists of only a single comment line does not seem to work.
If you have access to Python on your computer (which you do by default if you are on Mac OSX or Linux), then I would suggest trying your examples in a real Python interpreter. Otherwise, you might see some unexpected results, as I assume that repl.it is not a full-featured interpreter (as indicated by the syntax error).
It means Python is surprised that that the code ended without being finished. For your example, you didn't write any code, just a comment, without a blank line on the bottom?
Try print "This will not run" if that's the ONLY line of code in your file.
The python-interpreter is looking for code it shall execute but finds none, as the line you try to run is uncommented (by the # in the beginning).
Because it found no code to evaluate it makes some noise.
Remove the # and it will work...

Xcode All Exceptions Breakpoint - Ignore Certain C++ Exception

I'm coding in C++ for iOS, using certain iOS Frameworks like AVAudioPlayer. I know that these can trigger C++ exceptions internally and it's perfectly fine, since they catch and handle them.
I would like to use the All Exceptions Breakpoint in Xcode to break on Crash-Issues in my own C++ code, but to ignore that AVAudioPlayer's C++ exceptions (and basically all other catched exceptions).
How can I achieve that?
There isn't a way to do this using the Xcode breakpoint settings.
You can do this in lldb using a Python breakpoint command on the C++ exception breakpoint. Your callback would look up the stack to the point where the exception is thrown, and check that the throwing code is in your shared library, and auto-continue from the breakpoint or not.
The section in:
http://lldb.llvm.org/python-reference.html
on running a script when a breakpoint is hit will give you some details about how to do this.
For instance, you could put:
module_name = "TheNameOfYourExecutableOrSharedLibrary"
def bkpt_cmd (frame, loc, dict):
global module_name
thread = frame.GetThread()
frame_1 = thread.GetFrameAtIndex(1)
module = frame_1.GetModule()
name = module.GetFileSpec().GetFilename()
if module_name in name:
return True
return False
in a file called ~/bkpt_cmd.py. Then in the lldb console, do:
(lldb) br s -E c++
Breakpoint 1: no locations (pending).
(lldb) command script import ~/bkpt_cmd.py
(lldb) br com add -F bkpt_cmd.bkpt_cmd
This will set a C++ exception breakpoint that only triggers when the raising frame is in the shared library called "TheNameOfYourExecutableOrSharedLibrary"...
BTW, if you put the following def in your .py file:
def __lldb_init_module(debugger, internal_dict):
it will get run when the command script import command is executed, so you could use this to add the breakpoint and the command to the breakpoint at one go. I'll leave that as an exercise for the reader.
Note also, this will work when running lldb within Xcode, but you'll want to make your own exception breakpoint as shown above, since Xcode has a different way of handling the commands for the breakpoints it manages.

Why does exit(0) in TRY loop result in an exception being thrown? [duplicate]

This question already has answers here:
Is there a way to prevent a SystemExit exception raised from sys.exit() from being caught?
(3 answers)
Closed 6 years ago.
Consider the following example:
try:
print "Try this."
exit(0)
except:
print "Failed."
exit(1)
When this simple example is executed, the following is printed to stdout:
Try this.
Failed.
Forgive me if there is an obvious answer or if this has already been asked, but why does exit(0) (which should give me a clean exit) throw an exception?
I tried using a try: except: loop in an actual use-case script, and found that the script would exit(1) even when the try condition says to exit(0).
So I guess exit(0) is throwing a(n hidden?) exception of some sort, but why? It doesn't show the traceback (such as when CTRL + C is used to generate a KeyboardInterrupt exception), and results in unexpected behavior such as in my case when I'm expecting a 0 return and end up with a 1 return.
Is an exception (any exception) the only way to exit a python script?
The exception being raised here is SystemExit Exception. Hence, if you try:
try:
print "Try this."
exit(0)
except SystemExit:
pass
except:
print "Failed."
exit(1)
Output is:
Try this.
To prevent this, you can call os._exit() to directly exit, without throwing an exception:
import os
try:
print "Try this."
os._exit(0)
except SystemExit:
pass
except:
print "Failed."
os._exit(1)
Quoting user2357112:
os._exit skips finally blocks, context manager __exit__s, exit handlers, and other important cleanup, so outside of a few highly specific cases (I believe most of them involve fork), it's not a good idea to use it.

Restart Python script if finish or crash Windows

Now I have a infinite loop in my code for the script restart when finish. The problem is when script crash.
How I can restart script if crash?
infiniteloop.py
while True:
execfile("abc.py")
abc.py
print "1"
error
Do like this,
while True:
try:
execfile("abc.py")
except Exception as e:
print "Exception occured: ", e
There's probably not any way to have the script restart itself once it's crashed, but you could add some error handling like so:
while True:
try:
execfile("abc.py")
except:
pass
Alternatively, you could use shell scripting to run your wrapper repeatedly.