Last active
December 31, 2015 17:38
-
-
Save felix021/8021106 to your computer and use it in GitHub Desktop.
一个看起来好像没什么用的Python脚本。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import os | |
import sys | |
import compiler | |
fsrc = open(sys.argv[1]) | |
code = fsrc.read() | |
lines = code.split('\n') | |
fsrc.close() | |
stmt = compiler.parse(code).getChildNodes()[0].getChildNodes() | |
line_nos = map(lambda x: x.lineno, stmt) + [len(lines) + 1] | |
sub_globals = {} | |
sub_locals = {} | |
for i, (start, stop) in enumerate(zip(line_nos, line_nos[1:])): | |
block = lines[start-1:stop-1] | |
nr_empty_lines = 0 | |
for line in reversed(block): #trailing empty lines | |
if line.strip() == '': | |
nr_empty_lines += 1 | |
else: | |
break | |
if nr_empty_lines == 0: | |
codeblock = block | |
else: | |
codeblock = block[:-nr_empty_lines] | |
code = '\n'.join(codeblock) | |
if isinstance(stmt[i], compiler.ast.Discard): | |
code = '____ret = ' + code | |
print '>>>', block[0] | |
for line in block[1:-nr_empty_lines]: | |
print '...', line | |
if len(codeblock) > 1: | |
print '...' | |
nr_empty_lines = max(0, nr_empty_lines - 1) | |
try: | |
exec(code, sub_globals, sub_locals) | |
if isinstance(stmt[i], compiler.ast.Discard): | |
print sub_locals['____ret'] | |
except Exception, e: | |
print """Traceback (most recent call last): \n File "<stdin>", line 1, in <module>""" | |
print '%s: %s' % (e.__class__.__name__, e) | |
for i in range(nr_empty_lines): print '>>> ' #necessary? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment