source: branches/UQ/funcIO.py @ 855

Revision 855, 2.1 KB checked in by mmckerns, 5 months ago (diff)

updated copyright to 2016

Line 
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
8def 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
25def src(object):
26    """
27This is designed to work on simple functions (not general callables.)
28The 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
40HOLD = []
41def tmp_funcdump(func):
42    """ write func source to a NamedTemporaryFile (instead of pickle.dump)
43with a last line 'FUNC = <function>' to be included as module.FUNC
44hence you can arbitrarily import and call the funciton w/o knowing the name
45
46NOTE: 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
56def 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
64if __name__ == '__main__':
65  pass
66
67
68# EOF
Note: See TracBrowser for help on using the repository browser.