2016-05-20 7 views
2

対話モードで実行されているように、Pythonスクリプトの実行によって式の結果がトップレベルに自動的に書き込まれる方法を知りたいと思います。例えば非対話型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が私を助けてくれたようですが、私はそれを成功させることはできません。

答えて

4

まあ、私は真剣にこのようなものを使用して提案していないよ、しかし、あなたは(AB)は使用できast処理:

% python2 printer.py test2.py 
3 
1 
2 
3 
4 
5 

# -*- 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

関連する問題