我想找到一种方法,Python脚本的执行会自动在顶层写入表达式的结果,就像在交互模式下一样。
例如,如果我有script.py
:
abs(3)
for x in [1,2,3]:
print abs(x)
abs(-4)
print abs(5)
并执行python script.py
,我会得到
1
2
3
5
但我宁愿拥有
3
1
2
3
4
5
这是交互式执行它的模块(模数提示)。
或多或少,我想实现Disable automatic printing in Python interactive session的相反。似乎code
模块可以帮助我,但我没有成功。
答案 0 :(得分:4)
好吧,我并不认真提议使用这样的东西,但你可以(ab)使用ast
处理:
# -*- coding: utf-8 -*-
import ast
import argparse
_parser = argparse.ArgumentParser()
_parser.add_argument('file')
class ExpressionPrinter(ast.NodeTransformer):
visit_ClassDef = visit_FunctionDef = lambda self, node: node
def visit_Expr(self, node):
node = ast.copy_location(
ast.Expr(
ast.Call(ast.Name('print', ast.Load()),
[node.value], [], None, None)
),
node
)
ast.fix_missing_locations(node)
return node
def main(args):
with open(args.file) as source:
tree = ast.parse(source.read(), args.file, mode='exec')
new_tree = ExpressionPrinter().visit(tree)
exec(compile(new_tree, args.file, mode='exec'))
if __name__ == '__main__':
main(_parser.parse_args())
示例 script.py 的输出:
% python2 printer.py test2.py
3
1
2
3
4
5