gpt4 book ai didi

python - 当 __init__.py 破坏 pyinstaller 时如何正确导入文件

转载 作者:行者123 更新时间:2023-12-01 01:18:54 29 4
gpt4 key购买 nike

我已经解决了 pyinstaller 的问题,解决问题的方法是从我的树中删除空的 __init__.py 文件,所以我不有了该文件,一切都按预期进行。但是,现在我添加更多文件并具有不同的文件夹结构:

dist
|
+--- rating_service.exe # created by pyinstaller
service
|
+--- rating_service.py
shared
|
+--- resource_globals.py

在 rating_service.py 中,我尝试了这些导入并收到这些错误:

from . import shared

ImportError: cannot import name 'shared'

from .. import shared

ValueError: attempted relative import beyond top-level package

import shared

ModuleNotFoundError: No module named 'shared'

如何访问 rating_service 中的 resource_globals 内容?

最佳答案

如果添加任何 __init__.py 文件不可行,那么作为解决方法,您可以在 rating_service.py 代码文件中执行以下操作:

# -----------------
# rating_service.py
# -----------------
import os
import sys

# Manually add the 'shared' directory to the python search paths
file_dir = os.path.dirname(os.path.realpath(__file__))
shared_dir = os.path.join(file_dir, '../shared')
sys.path.insert(0, shared_dir)

import resource_globals

关于python - 当 __init__.py 破坏 pyinstaller 时如何正确导入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54030384/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com