|
| 1 | +"""The ucb module contains functions specific to 61A at UC Berkeley.""" |
| 2 | + |
| 3 | +import code |
| 4 | +import functools |
| 5 | +import inspect |
| 6 | +import re |
| 7 | +import signal |
| 8 | +import sys |
| 9 | + |
| 10 | + |
| 11 | +def main(fn): |
| 12 | + """Call fn with command line arguments. Used as a decorator. |
| 13 | +
|
| 14 | + The main decorator marks the function that starts a program. For example, |
| 15 | + |
| 16 | + @main |
| 17 | + def my_run_function(): |
| 18 | + # function body |
| 19 | + |
| 20 | + Use this instead of the typical __name__ == "__main__" predicate. |
| 21 | + """ |
| 22 | + if inspect.stack()[1][0].f_locals['__name__'] == '__main__': |
| 23 | + args = sys.argv[1:] # Discard the script name from command line |
| 24 | + fn(*args) # Call the main function |
| 25 | + |
| 26 | + |
| 27 | +PREFIX = '' |
| 28 | +def trace(fn): |
| 29 | + """A decorator that prints a function's name, its arguments, and its return |
| 30 | + values each time the function is called. For example, |
| 31 | +
|
| 32 | + @trace |
| 33 | + def compute_something(x, y): |
| 34 | + # function body |
| 35 | + """ |
| 36 | + @functools.wraps(fn) |
| 37 | + def wrapped(*args, **kwds): |
| 38 | + global PREFIX |
| 39 | + reprs = [repr(e) for e in args] |
| 40 | + reprs += [repr(k) + '=' + repr(v) for k, v in kwds.items()] |
| 41 | + log('{0}({1})'.format(fn.__name__, ', '.join(reprs)) + ':') |
| 42 | + PREFIX += ' ' |
| 43 | + try: |
| 44 | + result = fn(*args, **kwds) |
| 45 | + PREFIX = PREFIX[:-4] |
| 46 | + except Exception as e: |
| 47 | + log(fn.__name__ + ' exited via exception') |
| 48 | + PREFIX = PREFIX[:-4] |
| 49 | + raise |
| 50 | + # Here, print out the return value. |
| 51 | + log('{0}({1}) -> {2}'.format(fn.__name__, ', '.join(reprs), result)) |
| 52 | + return result |
| 53 | + return wrapped |
| 54 | + |
| 55 | + |
| 56 | +def log(message): |
| 57 | + """Print an indented message (used with trace).""" |
| 58 | + if type(message) is not str: |
| 59 | + message = str(message) |
| 60 | + print(PREFIX + re.sub('\n', '\n' + PREFIX, message)) |
| 61 | + |
| 62 | + |
| 63 | +def log_current_line(): |
| 64 | + """Print information about the current line of code.""" |
| 65 | + frame = inspect.stack()[1] |
| 66 | + log('Current line: File "{f[1]}", line {f[2]}, in {f[3]}'.format(f=frame)) |
| 67 | + |
| 68 | + |
| 69 | +def interact(msg=None): |
| 70 | + """Start an interactive interpreter session in the current environment. |
| 71 | +
|
| 72 | + On Unix: |
| 73 | + <Control>-D exits the interactive session and returns to normal execution. |
| 74 | + In Windows: |
| 75 | + <Control>-Z <Enter> exists the interactive session and returns to normal |
| 76 | + execution. |
| 77 | + """ |
| 78 | + # use exception trick to pick up the current frame |
| 79 | + try: |
| 80 | + raise None |
| 81 | + except: |
| 82 | + frame = sys.exc_info()[2].tb_frame.f_back |
| 83 | + |
| 84 | + # evaluate commands in current namespace |
| 85 | + namespace = frame.f_globals.copy() |
| 86 | + namespace.update(frame.f_locals) |
| 87 | + |
| 88 | + # exit on interrupt |
| 89 | + def handler(signum, frame): |
| 90 | + print() |
| 91 | + exit(0) |
| 92 | + signal.signal(signal.SIGINT, handler) |
| 93 | + |
| 94 | + if not msg: |
| 95 | + _, filename, line, _, _, _ = inspect.stack()[1] |
| 96 | + msg = 'Interacting at File "{0}", line {1} \n'.format(filename, line) |
| 97 | + msg += ' Unix: <Control>-D continues the program; \n' |
| 98 | + msg += ' Windows: <Control>-Z <Enter> continues the program; \n' |
| 99 | + msg += ' exit() or <Control>-C exits the program' |
| 100 | + |
| 101 | + code.interact(msg, None, namespace) |
0 commit comments