exec后的eval:看似相同的字符串并没有提供相同的结果(可能是编码问题)。

问题描述 投票:0回答:1

我定义了 _exec_ 函数,用于获取用字符串表示的函数的输出。例如 sgn 函数,用 arg 值(见下面的代码)。那么我将不得不在最后执行一个单一的评估。(警告。execeval 的未知代码,必须在使用前进行安全保护)。)

def _exec_(thecode):
    local = {}
    exec(thecode, globals(), local)
    return local["_output_"]

sgn = "\nif _input_[0]<0:\n    _output_ = -1\nif _input_[0]==0:\n    _output_ = 0\nif _input_[0]>0:\n    _output_ = 1"
arg = "[5]"

code_list = ["_input_ = "+arg+sgn]
print(eval("1+_exec_(code_list[0])"))

最后2行提供了良好的结果。然而,我将不得不用各种 "string-function "和 "string-arguments "来使用它,而且次数还不确定。是否可以只用1个命名的字符串而不是一个字符串列表?

我试了一下。

code = "1+_exec_(_input_ = "+arg+sgn+")"
print(eval(code))

结果是 SyntaxError: invalid syntax. 可能是特殊字符的编码有问题,然后我试了一下。

code = "1+_exec_(_input_ = "+arg+sgn.encode('unicode-escape').decode()+")"
print(eval(code))

结果是 SyntaxError: unexpected character after line continuation character. 我也试着用答案来解决 Python: exec()一个代码块和eval()最后一行。,但没有成功。

python python-3.x string eval
1个回答
1
投票

他们 不是 同样的字符串,"似乎 "或其他。只要把 eval 从两 print(eval(...)) 呼叫和比较。

>>> print("1+_exec_(code_list[0])")
1+_exec_(code_list[0])

vs:

>>> code = "1+_exec_(_input_ = "+arg+sgn+")"
>>> print(code)
1+_exec_(_input_ = [5]
if _input_[0]<0:
    _output_ = -1
if _input_[0]==0:
    _output_ = 0
if _input_[0]>0:
    _output_ = 1)

后面那条看起来并不像什么有效的语法。

© www.soinside.com 2019 - 2024. All rights reserved.