简体   繁体   English

内部使用exec(astring)和astring中的变量定义的函数不能返回python 3中的变量

[英]Function internally using exec(astring) with a variable definition inside astring can not return the variable in python 3

I have a python 3 function that takes a string of commands, say 'np.pi' and then tries to define a variable with that string. 我有一个python 3函数,它接受一串命令,比如'np.pi',然后尝试用该字符串定义一个变量。 Then I try to return the variable, this however does not work. 然后我尝试返回变量,但这不起作用。

input = np.pi
astring = 'funcD(funcC(funcB(funcA(input))))'

def function(astring):
  astring= 'variable = ' + astring
  exec(astring)
  return variable

In:  a = function(astring)
Out: NameError: global name 'variable' is not defined

Nothing seems to have happened. 似乎没有发生任何事情。 What I would like is to have the function return the output of the command in the string. 我想要的是让函数返回字符串中命令的输出。 The string contains several functions who have each other as input like below. 该字符串包含几个函数,这些函数彼此相互输入,如下所示。 I tried putting the exec after return without adding the variable = and then call the function with a = function(astring) but that did not work either. 我尝试在返回后放入exec而不添加变量=然后使用= function(astring)调用该函数,但这也不起作用。 I believe I cant use eval because my string has functions in it. 我相信我不能使用eval,因为我的字符串中有函数。

You didn't state what you expected from the answer, so I take a guess: You want to make this work. 你没有说明你对答案的期望,所以我猜一下:你想要做到这一点。

Try it using eval : 使用eval尝试:

def function(astring):
  astring= 'variable = ' + astring
  exec(astring)
  return eval('variable')

function('42')

returns as expected 42 . 按预期返回42

Or simply strip that assignment: 或者简单地删除该任务:

def function(astring):
  return eval(astring)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM