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?

3
  • execfile("filepath") Commented Dec 6, 2017 at 20:36
  • Because you I cannot reproduce this... Commented Dec 6, 2017 at 20:43
  • It would be helpful to mention Python3.6. 'execfile' does not work Commented Dec 6, 2017 at 20:48

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Is there a way to not have any variable associated "var". Directly access C
How would you access if x is in a different directory?
Doesn't that kind of defeat the purpose of x.py ? Wasn't it supposed to call files from different directory?
I wanted a single instruction which can do it in the shell. possible?
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 

1 Comment

What do I do if my Test is located in a different directory? (apart from path append)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.