| 1 | #!/usr/bin/env python |
|---|
| 2 | # |
|---|
| 3 | # Author: Mike McKerns (mmckerns @caltech and @uqfoundation) |
|---|
| 4 | # Copyright (c) 2009-2016 California Institute of Technology. |
|---|
| 5 | # License: 3-clause BSD. The full license text is available at: |
|---|
| 6 | # - http://mmckerns.github.io/project/mystic/browser/mystic/LICENSE |
|---|
| 7 | |
|---|
| 8 | def parse_from_history(object): |
|---|
| 9 | import readline, inspect |
|---|
| 10 | lbuf = readline.get_current_history_length() |
|---|
| 11 | code = [readline.get_history_item(i)+'\n' for i in range(1,lbuf)] |
|---|
| 12 | lnum = 0 |
|---|
| 13 | codeblocks = [] |
|---|
| 14 | while lnum < len(code)-1: |
|---|
| 15 | if code[lnum].startswith('def'): |
|---|
| 16 | block = inspect.getblock(code[lnum:]) |
|---|
| 17 | lnum += len(block) |
|---|
| 18 | if block[0].startswith('def %s' % object.func_name): |
|---|
| 19 | codeblocks.append(block) |
|---|
| 20 | else: |
|---|
| 21 | lnum +=1 |
|---|
| 22 | return codeblocks |
|---|
| 23 | |
|---|
| 24 | |
|---|
| 25 | def src(object): |
|---|
| 26 | """ |
|---|
| 27 | This is designed to work on simple functions (not general callables.) |
|---|
| 28 | The advantage is that it will work on functions defined interactively. |
|---|
| 29 | """ |
|---|
| 30 | import inspect |
|---|
| 31 | # no try/except (like the normal src function) |
|---|
| 32 | if hasattr(object,'func_code') and object.func_code.co_filename == '<stdin>': |
|---|
| 33 | # function is typed in at the python shell |
|---|
| 34 | lines = parse_from_history(object)[-1] |
|---|
| 35 | else: |
|---|
| 36 | lines, lnum = inspect.getsourcelines(object) |
|---|
| 37 | return ''.join(lines) |
|---|
| 38 | |
|---|
| 39 | |
|---|
| 40 | HOLD = [] |
|---|
| 41 | def tmp_funcdump(func): |
|---|
| 42 | """ write func source to a NamedTemporaryFile (instead of pickle.dump) |
|---|
| 43 | with a last line 'FUNC = <function>' to be included as module.FUNC |
|---|
| 44 | hence you can arbitrarily import and call the funciton w/o knowing the name |
|---|
| 45 | |
|---|
| 46 | NOTE: HOLD the return value for as long as you want your file to exist |
|---|
| 47 | """ |
|---|
| 48 | import tempfile |
|---|
| 49 | file = tempfile.NamedTemporaryFile(suffix='.py', dir='.') |
|---|
| 50 | file.write(''.join(src(func))) |
|---|
| 51 | file.write('FUNC = %s\n' % func.func_name) |
|---|
| 52 | file.flush() |
|---|
| 53 | return file |
|---|
| 54 | |
|---|
| 55 | |
|---|
| 56 | def func_load(modulename): |
|---|
| 57 | """ read function from a 'special' source file that has a line |
|---|
| 58 | 'FUNC = <function>' included as module.FUNC |
|---|
| 59 | """ |
|---|
| 60 | module = __import__(modulename) |
|---|
| 61 | return module.FUNC |
|---|
| 62 | |
|---|
| 63 | |
|---|
| 64 | if __name__ == '__main__': |
|---|
| 65 | pass |
|---|
| 66 | |
|---|
| 67 | |
|---|
| 68 | # EOF |
|---|