Reputation: 134
I have a project with folder structure like this:
MainFolder/
__init__.py
Global.py
main.py
Drivers/
__init__.py
a.py
b.py
In Global.py I have declared like this:
#in Global.py file
global_value=''
Now when I tried the below script:
#in main.py
import Global
from Drivers import a
Global.global_value=5
a.print_value()
In a.py file
from MainFolder import Global
def print_value():
print Global.global_value
The output supposed to be like this:
5
But all I am getting is :
''
Anyone with this solution what happens when context changes??
Upvotes: 0
Views: 83
Reputation: 2827
In my opinion you should not do that. To have some form of common value, write the value to a file/db and then fetch the value from that file.
If that doesn't suite the needs, here's some resources I found, might help you out:
I've not tested this, but this one should work (fetched from Import a module from a relative path)
import os, sys, inspect
# realpath() will make your script run, even if you symlink it :)
cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0]))
if cmd_folder not in sys.path:
sys.path.insert(0, cmd_folder)
# use this if you want to include modules from a subfolder
cmd_subfolder = os.path.realpath(os.path.abspath(os.path.join(os.path.split(inspect.getfile( inspect.currentframe() ))[0],"subfolder")))
if cmd_subfolder not in sys.path:
sys.path.insert(0, cmd_subfolder)
# Info:
# cmd_folder = os.path.dirname(os.path.abspath(__file__)) # DO NOT USE __file__ !!!
# __file__ fails if script is called in different ways on Windows
# __file__ fails if someone does os.chdir() before
# sys.argv[0] also fails because it doesn't not always contains the path
More:
Upvotes: 1