Interrupting `while loop` with keyboard in Cython - c++

I want to be able to interrupt a long function with cython, using the usual CTRL+C interrupt command.
My C++ long function is repeatedly called inside a while loop from Cython code, but I want to be able, during the loop, to send an "interrupt" and block the while loop.
The interrupt also should wait the longFunction() to finish, so that no data are lost or kept in unknown status.
This is one of my first implementation, which obviously doesn't work:
computed=0;
print "Computing long function..."
while ( computed==0 ):
try:
computed = self.thisptr.aLongFunction()
except (KeyboardInterrupt, SystemExit):
computed=1
print '\n! Received keyboard interrupt.\n'
break;
(p.s. self.thisptr is the pointer to the current class which implements aLongFunction() )

You should be able to do something like this:
import signal
class Test():
def __init__(self):
self.loop_finished = False
signal.signal(signal.SIGINT, self.abort_loop)
def abort_loop(self, signal, frame):
self.loop_finished = True
def go(self):
while not self.loop_finished:
print "Calculating"
# Do your calculations
# Once calcations are done, set self.loop_finished to True
print "Calculating over"
Test().go()
You can also use additional variables to keep track of whether the computation was manually aborted or not.

I am not a Python C-Api foo master, however this works, but maybe its not the best way:
cdef extern from "Python.h":
int PyErr_CheckSignals()
def test_interrupt():
cdef int i = 0
while i < 9999999999 and not PyErr_CheckSignals():
# do fancy stuff.
i += 1
Of course that is not asynchronous which is maybe possible but I do not know and this breaks the loop for any signal, not just Ctrl+C. Also maybe its better to not check signals every loop iteration, at least if what is done is very cheap.
You could call PyErr_Occurred, etc. if PyErr_CheckSignals did not return 0 and see what kind of Exception got raised to go specifically for KeybordInterrupt or certain kill signals. (Anyway, check the python C-Api for details there...)
If you are calling a cython cdef function inside the while loop you may be able to achieve this also if you add except *:
cdef function(...) except *:
pass
see also http://docs.cython.org/src/userguide/language_basics.html#error-return-values

Related

How to understand this code in terms of building and evaluating a stack?

I was recently trying to solve a challenge on Hackerrank which asked us to figure out whether a string containing brackets (e.g. {}, (), and [] ) was balanced or not (source: https://www.hackerrank.com/challenges/balanced-brackets). I wanted to solve this using the following approach that also integrated the initial format Hackerrank provided:
import sys
def isBalanced(s):
#insert code here
if __name__ == "__main__":
t = int(raw_input().strip())
for a0 in xrange(t):
s = raw_input().strip()
result = isBalanced(s)
print result
I should also note that site has configured the following as being the standard input in order to test the functionality of the code:
3
{[()]}
{[(])}
{{[[(())]]}}
In order to get the following output:
YES
NO
YES
However, I didn't understand how to approach this code, chiefly because I did not understand why Hackerrank used the if __name__ == "__main__": clause, as I thought that this clause was only used if someone wanted their module to be executed directly rather than executed through being imported in another script (source: What does if __name__ == "__main__": do?). I also did not understand the for loop containing for a0 in xrange(t): since a0 is not used within the for loop for anything, so I'm really unsure how the standard input would be processed.
So I ended up looking up the solution on the discussion page, and here it is below:
lefts = '{[('
rights = '}])'
closes = { a:b for a,b in zip(rights,lefts)}
def valid(s):
stack = []
for c in s:
if c in lefts:
stack.append(c)
elif c in rights:
if not stack or stack.pop() != closes[c]:
return False
return not stack # stack must be empty at the end
t = int(raw_input().strip())
for a0 in xrange(t):
s = raw_input().strip()
if valid(s):
print 'YES'
else:
print 'NO'
This code also confuses me, as the writer claimed to utilize a data structure known as a "stack" (although it seems to be just a Python list to me). And although the writer removed the if __name__ == "__main__": statement, they retained the for a0 in xrange(t):, which I'm not sure how it processes the standard input's integer and corresponding strings.
Furthermore, although the isBalanced function confuses me because it returns not stack. In a hash comment on the return statement of the function, the writer also states the # stack must be empty at the end. What does that mean? And how could this list be empty if, during the clause if c in lefts:, the stack is appended with the character of the string that is being iterated in the for-loop. So why would the function return not stack? Wouldn't it be consistent to return True so that the function would act as a Boolean tester (i.e. would return true if a certain object adhered to certain criteria, and false if the the object did not)?
I am still relatively new to coding so there are a lot of principles I am not familiar with. Can anyone illuminate as to how this would work?
iam not sure how your code works .. if name == "main": do?). just exlained where you use of Before executing the code, it will define a few special variables. For example, if the python interpreter is running that module (the source file) as the main program, it sets the special name variable to have a value "main". If this file is being imported from another module, name will be set to the module's name

Python tk(): No window appears when using in scripts (console works)

I have the following problem with this easy script:
from Tkinter import *
root = Tk()
while 1:
pass
I think, after the 2nd line everyone would expect a Tkinter window would appear. But it does not!
If I put this line into the Python console (without the endless-while-loop), it works.
[I wanted to add an image here, but as I'm new I'm to allowed to :-(]
But running the script (double-clicking on the *.py file in the Windows Explorer) results only in an empty Python console!
Background:
Actually I want to use Snack for Python. This is based on Tkinter. That means I have to create an Tk() instance first. Everything works fine in the Python console. But I want to write a bigger program with at least one Python script thus I cannot type the whole program into the console everytime :-)
I have installed Python 2.7 and Tcl/Tk 8.5 (remember: it works in the console)
EDIT: So here's my solution:
First, I create a class CSoundPlayer:
from Tkinter import*
import tkSnack
class CSoundPlayer:
def __init__(self, callbackFunction):
self.__activated = False
self.__callbackFunction = callbackFunction
self.__sounds = []
self.__numberOfSounds = 0
self.__root = Tk()
self.__root.title("SoundPlayer")
tkSnack.initializeSnack(self.__root)
def __mainFunction(self):
self.__callbackFunction()
self.__root.after(1, self.__mainFunction)
pass
def activate(self):
self.__activated = True
self.__root.after(1, self.__mainFunction)
self.__root.mainloop()
def loadFile(self, fileName):
if self.__activated:
self.__sounds.append(tkSnack.Sound(load=fileName))
self.__numberOfSounds += 1
# return the index of the new sound
return self.__numberOfSounds - 1
else:
return -1
def play(self, soundIndex):
if self.__activated:
self.__sounds[soundIndex].play()
else:
return -1
Then, the application itself must be implemented in a class thus the main() is defined when handed over to the CSoundPlayer() constructor:
class CApplication:
def __init__(self):
self.__programCounter = -1
self.__SoundPlayer = CSoundPlayer(self.main)
self.__SoundPlayer.activate()
def main(self):
self.__programCounter += 1
if self.__programCounter == 0:
self.__sound1 = self.__SoundPlayer.loadFile("../mysong.mp3")
self.__SoundPlayer.play(self.__sound1)
# here the cyclic code starts:
print self.__programCounter
CApplication()
As you can see, the mainloop() is called not in the constructor but in the activate() method. This is because the CApplication won't ever get the reference to CSoundPlayer object because that stucks in the mainloop.
The code of the class CApplication itself does a lot of overhead. The actual "application code" is placed inside the CApplication.main() - code which shall be executed only once is controlled by means of the program counter.
Now I put it to the next level and place a polling process of the MIDI Device in the CApplication.main(). Thus I will use MIDI commands as trigger for playing sound files. I hope the performance is sufficient for appropriate latency.
Have you any suggestions for optimization?
You must start the event loop. Without the event loop, tkinter has no way to actually draw the window. Remove the while loop and replace it with mainloop:
from Tkinter import *
root = Tk()
root.mainloop()
If you need to do polling (as mentioned in the comments to the question), write a function that polls, and have that function run every periodically with after:
def poll():
<do the polling here>
# in 100ms, call the poll function again
root.after(100, poll)
The reason you don't need mainloop in the console depends on what you mean by "the console". In IDLE, and perhaps some other interactive interpreters, tkinter has a special mode when running interactively that doesn't require you call mainloop. In essence, the mainloop is the console input loop.

issue with inlinecallbacks twisted

i am writing twisted code .. first one with deferred second one with inlineCallbacks. first one works but second doesn't .. any idea or pointers
class Echo(LineReceiver):
def lineReceived_callbacks(self, line):
print self.sendLine("i received :%s"%line)
def pp(res):
print "from callback",res
self.sendLine(str(res))
d = self.factory.dbs.getResult(line)
d.addCallback(pp)
#defer.inlineCallbacks
def lineReceived(self, line):
res = yield self.factory.dbs.getResult(line)
print res
self.sendLine(str(res))
self.factory.dbs.getResult(line) returns a deferred.
got solution..
seems like a issue in twisted.
http://twistedmatrix.com/pipermail/twisted-python/2006-October/014277.html
if lineReceived returns a deferred connection drops in defer example deferred is created but not returned and in second because using inlineCallbacks, it returns deferred always and hence connection drop .. lineReceived is basic stuff and should be workable with inlineCallbacks..

python function passed into another function as argument

I am new to pragramming and python. This is something like what I have.
Def some_function():
Print "stuff"
Def another_function(x):
running = True
While running:
x
another_function(some_function())
Why does it only print "stuff" the first time going through the loop?
I read some stuff that talked about late binding but not sure if that is what this is or how to fix it in my example.
You didn't pass the function, you called the function and passed its value. So it printed stuff before you ever got into the loop.
To refer to a function without calling it, you leave off the (). So it should be:
another_function(some_function);
Then in another_function, you have to call the function:
def another_function(x):
running = True
while running:
x()

Pruning backtrace output with gdb script

My program has 100 threads, most of which are idle and share a very well defined backtrace when they are idle. Most of the time I am only interested in the threads that are not idle and therefore do not have the "common" backtrace. I thought using a gdb script would be a good way to do this.
define backtraces
thread apply all bt
end
This script will simply print all the backtraces. Is there a way to store this output into a variable that I can then process, prune, and display only the relevant backtraces?
I naively tried:
define backtraces
set $bts = thread apply all bt
// do whatever processing here
end
But that fails with following as expected:
No symbol "thread" in current context.
Is there a better way to do this? Or good tutorials on how to power script in gdb?
Is there a better way to do this?
You would need to use Python scripting to achieve your desired result.
The filtering backtrace is probably a good start.
Using the links in Employed Russian's answer I was able to get something working. Here it is for posterity since it was completely non-obvious.
import gdb
# This loops through all the Thread objects in the process
for thread in gdb.selected_inferior().threads():
# This is equivalent to 'thread X'
thread.switch()
print "Thread %s" % thread.num
# Just execute a raw gdb command
gdb.execute('bt')
framesNames = []
f = gdb.newest_frame()
while f is not None:
framesNames.append(gdb.Frame.name(f))
f = gdb.Frame.older(f)
# do something with the name of each frame
If this were in a file named traces.py, then from gdb you can just execute the python:
source traces.py
There are other ways to invoke this python script too.
This is what I came out with based on JaredC wrote:
import gdb
class FilteredThreadBacktraceCommand(gdb.Command):
"""
Implements a command that allows printing the backtrace only for threads
that do not have given frames.
The class must be instantiated with a list of the frames to ignore. If the
stack for a thread has any of those frames then the stack for that thread
will not be printed (a visual dot will be printed to show a thread was just
ignored and provide a notion of progress).
"""
def __init__(self, ignored_frames):
super (FilteredThreadBacktraceCommand, self).__init__ ("fbt", gdb.COMMAND_STACK)
self.ignored_frames = ignored_frames
def invoke(self, arg, from_tty):
args = gdb.string_to_argv(arg)
if len(args) != 0:
gdb.write("ERROR: invalid number of arguments.\n")
return
# This loops through all the Thread objects in the process
for thread in gdb.selected_inferior().threads():
# This is equivalent to 'thread X'
thread.switch()
f = gdb.newest_frame()
frames = []
invalid_thread = False
while f is not None:
if any(ignored_frame in f.name() for ignored_frame in self.ignored_frames):
invalid_thread = True
break
frames.append(f)
f = gdb.Frame.older(f)
if invalid_thread:
# Visual effect as iterating frames might take a while
sys.stdout.write('.')
sys.stdout.flush()
continue
print "\nThread %s:" % thread.num
for i in range(len(frames)):
f = frames[i]
funcInfo = f.function()
printStr = "#{} in {}".format(i, f.name())
if f.function():
printStr += " at {}:{}".format(funcInfo.symtab.filename, funcInfo.line)
else:
printStr += " at (???)"
print(printStr)
FilteredThreadBacktraceCommand(["os::PlatformEvent::park"])
You can provide the frames that you want to ignore to the class on creation. One could also make this generic so as to provide a name to the command to register as well so that you could have different commands with different filtering.