在Python中将变量从一个文件导入到另一个文件

slsn1g29  于 2023-06-25  发布在  Python
关注(0)|答案(1)|浏览(134)

我正在做一个个人项目,这是我的目录结构:

app/
-- function/
-- -- run.py
-- constants.py

我在constants.py中定义了一些变量,希望导入它们并在run.py中使用它们。
我试过以下几种方法,但似乎都失败了:

from ..constants import VARIABLE

这一个扔了ImportError: attempted relative import with no known parent package

from app.constants import VARIABLE

这一个扔了ModuleNotFoundError: No module named 'app'
我希望能够读取constants.py中定义的VARIABLErun.py中并在那里使用。
我该怎么办?我不是在寻找一个变通办法,我想要的东西,我可以复制在多个不同的项目。

qoefvg9y

qoefvg9y1#

1.使用sys.path. append()函数OR
1.使用importlib Packag或
1.使用SourceFileLoader类
sys.path.append("module_path")

# importing module
import sys

# appending a path
sys.path.append('articles')

# importing required module
import gfg
from gfg import GFG

# accessing its content
GFG.method_in()
gfg.method_out()

use this:)

相关问题