简体   繁体   English

使用exec在具有globals()的函数中执行文件

[英]Use exec to execute a file inside a function with globals()

I need to execute a file inside a python shell. 我需要在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 “ Test.py”将设置变量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. 我已经通过了全局变量,但是我仍然无法从exec访问变量。 References: 参考文献:

In Python, why doesn't an import in an exec in a function work? 在Python中,为什么在函数中的exec中导入不起作用?

How to execute a file within the python interpreter? 如何在python解释器中执行文件?

use import instead 改用import

from Test import C
print C

EDIT: 编辑:

If Test.py is in a different directory, you have to modify the sys.path 如果Test.py位于其他目录中,则必须修改sys.path

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

from Test import C
print C

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 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM