My setup is this. I have an engine.py
that defines a lot of variables and custom functions that I script and modify in external script.customextension
. I am using imp.load_source('script', 'script.customextension')
to import my external scripts, but when I do that all the variables and functions can not be accesssed from the external module.
I have then tried writing this as the first line in the external script: from engine import *
but then I am re-instantiating all the objects and losing the ones already created that I need access to.
A gross simplification is the following
file engine.py
a = 10
def f(myval):
global a
a = myval
print(a)
if __name__ == '__main__':
imp.load_source('script', 'script.ext')
and file script.ext
has this single line
f(20)
Results in this when running engine.py:
NameError: name 'f' is not defined
Where what I wanted was:
20
Here's ugly:
import __main__ as main
main.f(20)
I found that this solution could be used instead of importing modules (see exec
)
_file = open('script.ext')
for line in _file:
exec(line)
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.