1

I'm solving some text2code problem for question-answering system and in the process I had the following question: Is it possible to run strings of code as complete code by passing arguments from the original environment? For example,I have these piece of code in str:

import module    
model=module(data,*args)

And from base environment I want to do:

#for example
args=[**some args**]
data=pd.DataFrame()
exec(string)(data=data,*args)

For obvious reasons, transferring the data object using string.format() will not work. Standard unpacking using * does not work either, although, perhaps, I am doing something wrong.

  • Does this answer your question? [How do I execute a string containing Python code in Python?](https://stackoverflow.com/questions/701802/how-do-i-execute-a-string-containing-python-code-in-python) – jkr Mar 31 '21 at 13:16

1 Answers1

1

exec can take 3 args: the string, globals var and locals var.

So you can do something like:

exec(string, globals(), locals())

to pass all variable. It might be faster to only pass a subset of it:

exec(string, None, {k: locals()[k] for k in ('data', 'args')})`

For single expression you can use eval:

>>> i = 50
>>> eval("print(i)")
50
>>>

How do I execute a string containing Python code in Python?

politinsa
  • 3,480
  • 1
  • 11
  • 36
  • eval is only suitable for executing single expressions, it is not capable of executing a string as full source code:( – Valentine Sol Mar 31 '21 at 13:05
  • Yep,it works.It was only necessary to indicate the names of the arguments in the string itself, for some reason I did not think of this right away.Thanks! – Valentine Sol Mar 31 '21 at 13:23