Alright then, to actually set an "exit point" exactly where I want without touching the code is not so trivial.
It can be done however, I think, playing around with sys.settrace, as shown here
http://www.doughellmann.com/PyMOTW/sys/tracing.html
So the solution for me is to actually modify the code, simply adding an exit line at some point.
I wanted to use the difflib but it doesn't have patching functions, so I created the small script below, which in short:
- reads the file
- insert / deletes one line (on insertion with the same indentation as the previous line)
- rewrite it
#TODO: must make sure about the indentation
import argparse
import re
import sys
PATCH_LINE = "import sys; sys.exit(0) # PATCHED"
def parse_arguments():
# take the file and the line to patch, or maybe we can take a
# diff file generated via uniform_diff
parser = argparse.ArgumentParser(description='enable and disable the automatic exit')
parser.add_argument('file', help='file to patch')
parser.add_argument('line', help='line where to quit')
parser.add_argument('-m', '--msg',
default=PATCH_LINE)
parser.add_argument('-d', '--disable',
action='store_true')
return parser.parse_args()
if __name__ == '__main__':
ns = parse_arguments()
text = open(ns.file).readlines()
line_no = int(ns.line)
if ns.disable:
# the line should not be necessary in that case?
text.remove(text[line_no])
else:
# count spaces
prev = text[line_no - 1]
m = re.match('\s*', prev)
to_insert = m.group() + ns.msg
print("inserting line %s" % to_insert)
text.insert(line_no, to_insert)
open(ns.file, 'w').writelines(text)