Skip to content

Instantly share code, notes, and snippets.

@felix021 felix021/magicpython
Last active Dec 31, 2015

Embed
What would you like to do?
一个看起来好像没什么用的Python脚本。
#!/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
You can’t perform that action at this time.