Search code examples
pythonpython-3.xsubprocesseval

How to use eval to run other python script with argument?


I have a python file a.py containing code:

var=50*10
data= # eval here to call add function of b.py with argument var
print(data)

and b.py contains code :

def add(h):
    res=h+10
    return res

Now what i want is to use eval to call run function of b.py from a.py python script with argument and get the result. but i am not able to understand how eval works here. I had looked at python official docs and they are beyond my understanding. or if not eval then what are the other options (except using other file as module)


Solution

  • eval() is a method for evaluation of expressions only. Thus, you can't use other statements. Since import is a statement, you can't use it in eval().

    what are the other options (except using other file as module)

    exec() works together with import, so a combination of exec() and eval() works:

    var = 50 * 10
    exec("import b")
    data = eval("b.add(var)")
    print(data)
    

    Or even exec() without eval():

    var = 50 * 10
    exec("import b\ndata=b.add(var)")
    print(data)
    

    Note:

    • IDEs may likely complain that data is undefined in the last version of the code
    • exec() is even more dangerous than eval()