Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'm not sure how or if this would work on windows, but under unix, you could do something like:</p> <pre><code>import signal import sys count = 0 def handler(signum,frame): global count print "Value of 'i' is",i count += 1 if count &gt;= 2: sys.exit(0) signal.signal(signal.SIGINT,handler) i = 0 while True: i += 1 </code></pre> <p>Here I exit the program after ctrl-C is caught (twice) because I don't have any other good way of exiting the program.</p> <p>The use of global data here is merely for demonstration purposes -- Out in the wild, I'd use a class and pass an instance-method to the signal handler in order to maintain state between calls. -- e.g., something like:</p> <pre><code>import signal class Reporter(object): def __init__(self): self.retval = [] def handler(self,signum,frame): print self.retval r = Reporter() signal.signal(signal.SIGINT,r.handler) </code></pre> <p>And then you can just re-bind <code>self.retval</code> whenever you enter/exit your function:</p> <pre><code>import os def search(path,filename): global found folders = [] retval = [] r.retval = retval #&lt;--- Line added try: for item in os.listdir(path): if not os.path.isfile(os.path.join(path, item)): folders.append(os.path.join(path, item)) else: if item == filename: found += 1 retval.append(os.path.join(path, item)) except WindowsError,e: print str(e)[10:] for folder in folders: retval += search(folder,filename) r.retval = retval #&lt;---- Line added return retval found = 0 path = 'C:\\' filename = 'test.txt' print search(path,filename) </code></pre> <p>I think I would prefer a non-recursive solution using <code>os.walk</code> however:</p> <pre><code>import os def search(path,filename): retval = [] r.retval = retval for (dirpath, dirnames, filenames) in os.walk(path): retval.extend(os.path.join(path,dirpath,item) for item in filenames if item == filename) return retval path = 'C:\\' filename = 'test.txt' print search(path,filename) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload