python中的值更改和上下文更改

2024-09-28 23:26:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件夹结构如下的项目:

MainFolder/
    __init__.py
    Global.py
    main.py
Drivers/
    __init__.py
    a.py
    b.py

在全局.py我宣布如下:

#in Global.py file
global_value=''

现在当我尝试下面的脚本时:

#in main.py
import Global
from Drivers import a
Global.global_value=5
a.print_value()

在.py文件中

from MainFolder import Global
def print_value():
    print Global.global_value

输出应该是这样的:

5

但我得到的只是:

''

有没有人用这个解决方案当上下文改变时会发生什么??你知道吗


Tags: 项目infrompyimport文件夹initvalue
1条回答
网友
1楼 · 发布于 2024-09-28 23:26:56

我认为你不应该那样做。要获得某种形式的公共值,请将该值写入文件/db,然后从该文件中获取该值。你知道吗

如果这还不能满足您的需要,下面是我找到的一些资源,可能会对您有所帮助:

我没有测试过这个,但是这个应该可以用(从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

更多:

相关问题 更多 >