2012-10-02 8 views
8

私は、次のタブインデント文字列evalにしようとしています:それは文句を言っている何を:「行1、無効な構文エラーがありました」Pythonのeval()がこの複数行の文字列を拒否しているのはなぜですか?

'''for index in range(10): 
     os.system("echo " + str(index) + "") 
''' 

を私は、取得しますか?私はeval()文に合わせてインデントする必要がありますか、それを文字列ファイルや一時ファイルに書き込んで実行する必要がありますか?

おかげで、

答えて

20

eval5+3

execようなものがcompile()を使用して、あなたが最初のコードオブジェクトに変換する必要がありevalで、このようなステートメントを使用するにはfor ...

>>> eval("for x in range(3):print x") 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<string>", line 1 
    for x in range(3):print x 
    ^
SyntaxError: invalid syntax 
>>> exec("for x in range(3):print x") 
0 
1 
2 
>>> eval('5+3') 
8 
+0

あなたの答えはここでした!これをDupeとしてマークする必要があります:P –

+0

lol私はこれについてすべてを忘れました:P –

+0

私はここからこれを捕まえましたhttp:// stackoverflow。com/questions/30671563/eval-not-working-on-multi-line-string#comment49405263_30671563:D –

11

ようなものを実行評価:

In [149]: import os 

In [150]: cc = compile('''for index in range(10): 
    os.system("echo " + str(index) + "")''','abc','single') 

In [154]: eval cc 
--------> eval(cc) 
0 
Out[154]: 0 
1 
Out[154]: 0 
2 
Out[154]: 0 
3 
Out[154]: 0 
4 

In [159]: cc = compile("2+2", 'abc', 'single') # works with simple expressions too 

In [160]: eval cc 
--------> eval(cc) 
Out[160]: 4 


>>> help(compile) 

compile(...) 
    compile(source, filename, mode[, flags[, dont_inherit]]) -> code object 

    Compile the source string (a Python module, statement or expression) 
    into a code object that can be executed by the exec statement or eval(). 
    The filename will be used for run-time error messages. 
    The mode must be 'exec' to compile a module, 'single' to compile a 
    single (interactive) statement, or 'eval' to compile an expression. 
    The flags argument, if present, controls which future statements influence 
    the compilation of the code. 
    The dont_inherit argument, if non-zero, stops the compilation inheriting 
    the effects of any future statements in effect in the code calling 
    compile; if absent or zero these statements do influence the compilation, 
    in addition to any features explicitly specified. 
+2

いつも良い答えと私が気づいていなかったpythonの機能 –

5

式を評価し(eval)、文を実行します(exec)。

参照:Expression Versus Statement

Expression: Something which evaluates to a value. Example: 1+2/x
Statement: A line of code which does something. Example: GOTO 100

2

(本番にこのようなコードを置く前に、最後にデフォルトのセキュリティ警告を参照してください!)

他の回答はexecevalとの違いを説明するのは良い仕事をします。

それでも、私は自分自身を書くことx=1; y=2; x+yではなく、力の人々のように入力を取りたいと思った:機能のこの種を構築するためのコードの

def f(): 
    x = 1 
    y = 2 
    return x + y 

文字列操作は危険なビジネスです。

私は、次のアプローチを使用して終了:

def multiline_eval(expr, context): 
    "Evaluate several lines of input, returning the result of the last line" 
    tree = ast.parse(expr) 
    eval_expr = ast.Expression(tree.body[-1].value) 
    exec_expr = ast.Module(tree.body[:-1]) 
    exec(compile(exec_expr, 'file', 'exec'), context) 
    return eval(compile(eval_expr, 'file', 'eval'), context) 

これは、Pythonのコードを解析し、 astライブラリを使用して、最後の行から離れたすべてのものを再構築します。最後の行は、前者を実行し、後者を評価します。

これは、あなたがevalに接続する必要が義務付けセキュリティ警告でセキュリティ警告。特権を持たないユーザによって提供されるコードは Evalexecであり、当然のことながら安全ではありません。このような場合は、別のアプローチを使用するか、ast.literal_evalを使用することをお勧めします。 evalexecは、実際にあなたのユーザにpythonの完全な表現力を与えたい場合を除き、悪い考えです。

関連する問題