简体   繁体   中英

Using the “exec()” command from a function inside an import, not affecting the main file's variables

I am currently making a module which exports the local variables to a python readable file and imports it through exec, but I am unable to modify them without using returns (Which is the whole idea). The problem boils down to:

I have two files, a module (module.py) and a main (main.py). I want the module to be able to execute code inside the main:

#module.py
def foo():
    exec("b = a")
#main.py
from module import foo
a = 10
foo()
print(b)

Expected outcome

10

Actual outcome

NameError: name 'b' is not defined

You can use __main__

main.py:

from module import foo
import __main__
a = 10
__main__ = foo(__main__)
print(b)

module.py:

def foo(main):
    main.b = main.a
    return main

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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