0

I need to execute a file inside a python shell.

I can

exec(open('Test.py').read())

But I need to call it from inside a function.

"Test.py" will set variable C=10

So,

#x.py
def load(file):
    exec(open(file).read(),globals())

>>> import x
>>> x.load('Test.py')
>>> C
>>> NameError: name 'C' is not defined

I have passed in the globals, but I still cant access the varibales from exec. References:

In Python, why doesn't an import in an exec in a function work?

How to execute a file within the python interpreter?

Chinmoy Kulkarni
  • 187
  • 1
  • 13

2 Answers2

0

use import instead

from Test import C
print C

EDIT:

If Test.py is in a different directory, you have to modify the sys.path

import sys.path
sys.path.insert(0, "path_to_directory")

from Test import C
print C
TallChuck
  • 1,725
  • 11
  • 28
0

So here is one way to do it

#x.py
def load(file):
    exec(open(file).read())
    return locals()

>>> import x
>>> var = x.load('Test.py')
>>> locals().update(var)
>>> C
>>> 10

Hope it helps

CodeCollector
  • 468
  • 2
  • 13