File: astdump.py

package info (click to toggle)
jython 2.5.1-2
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 41,624 kB
  • ctags: 101,579
  • sloc: python: 351,444; java: 204,338; xml: 1,316; sh: 330; ansic: 126; perl: 114; makefile: 94
file content (66 lines) | stat: -rwxr-xr-x 1,858 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/env python
import os
import globwalk
import astview

def makepath(path):
    """
    from holger@trillke.net 2002/03/18
    See: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/117243
    """

    from os import makedirs
    from os.path import normpath,dirname,exists,abspath

    dpath = normpath(dirname(path))
    if not exists(dpath): makedirs(dpath)
    return normpath(abspath(path))

def main(code_path, output_dir, testfile=False):
    if os.path.exists(output_dir):
        print "%s already exists, exiting" % output_dir
        sys.exit(1)
    os.mkdir(output_dir)
    if testfile:
        pyfiles = [f.rstrip() for f in file(code_path)]
    elif os.path.isdir(code_path):
        pyfiles = globwalk.GlobDirectoryWalker(code_path, "*.py")
    else:
        pyfiles = [code_path]

    for pyfile in pyfiles:
        import pprint
        path = pyfile.split(os.path.sep)
        print "%s to %s: %s" % (pyfile, output_dir, os.path.join(output_dir, *path))
        fh = open(makepath(os.path.join(output_dir, *path)), 'w')
        print fh
        pprint.pprint(astview.tree(pyfile), fh)

if __name__ == '__main__':
    import sys
    import getopt

    usage = """\
Usage: python %s [-t] code_path output_dir
       output_dir must not exist (it will be created)
       unless -t is specified, if codepath is a file test it, if codepath is a directory
             test all .py files in and below that directory.
""" % sys.argv[0]

    testfile = False
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'th')
    except:
        print usage
        sys.exit(1)
    for o, v in opts:
        if o == '-h':
            print usage
            sys.exit(0)
        if o == '-t':
            testfile = True
    if len(args) < 2 or len(args) > 3:
        print usage
        sys.exit(1)

    main(args[0], args[1], testfile)