Usage: %trace (enable|disable) [file pattern] [output path]

def trace(line):
    """Usage: %trace (enable|disable) [file pattern] [output path]"""
    args = line.split()
    enable = args[0] in {'enable', 'on'}

    if not enable:
        sys.settrace(None)
        sys.stdout = _ORIGINAL_STDOUT
        return

    pattern = args[1] if len(args) > 1 else None
    sys.stdout = open(args[2], 'a') if len(args) > 2 else sys.stdout
    sys.settrace(partial(trace_line, pattern))