Search code examples
pythonpython-3.xvariablesincludeexec

Pass variables to python script included using exec(open().read())


I'm getting an error while trying to access a variable from a function which is included using exec(open().read()).

But here I'm able to access the function printName(). Is there any other way without using subprocess?

I'm using python 3.7

main.py

age = 32
def printName(name):
    print(name)
exec(open("action.py").read())

action.py

printName("John")
print(age)

John

NameError: name age is not defined


Solution

  • I tried this code you are mentioned is working I think you are running action.py technically you need to run the main.py file that contained this code.

    age = 32
    def printName(name):
        print(name)
    exec(open("action.py").read())
    

    enter image description here