fix: 修复输出路径问题 — 路径解析改为基于应用目录而非CWD

当从外部目录(如D:\ccc)拖入文件时,输出文件会错误地写入源目录。
根因是所有路径使用相对路径 + os.getcwd() 解析,CWD不同则路径错误。

修复方案:
- ConfigManager.get_path() 改为使用 app_root (exe所在目录/脚本所在目录)
- 将 22 处裸硬编码 "data/result"/"data/output" 替换为 config.get_path()
- 添加 result_folder 到默认配置和 config.ini
- 修复 error_utils.py 中的路径匹配字符串

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-05-04 23:05:10 +08:00
parent 6fd14b4e49
commit 6f96bf50ac
18 changed files with 84 additions and 271 deletions
+1
View File
@@ -19,6 +19,7 @@ DEFAULT_CONFIG = {
'Paths': {
'input_folder': 'data/input',
'output_folder': 'data/output',
'result_folder': 'data/result',
'temp_folder': 'data/temp',
'template_folder': 'templates',
'template_file': '银豹-采购单模板.xls',
+12 -3
View File
@@ -33,7 +33,16 @@ class ConfigManager:
def _init(self, config_file):
"""初始化配置管理器"""
self.config_file = config_file or 'config.ini'
# 计算应用根目录(不依赖 os.getcwd()
import sys
if getattr(sys, 'frozen', False):
# PyInstaller 打包后,根目录是 exe 所在目录
self.app_root = os.path.dirname(sys.executable)
else:
# 源码运行,根目录是 app/config/ 的上两级
self.app_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
self.config_file = config_file or os.path.join(self.app_root, 'config.ini')
self.config = configparser.ConfigParser()
self.load_config()
@@ -153,8 +162,8 @@ class ConfigManager:
path = Path(path_str)
if not path.is_absolute():
# 相对路径,转为绝对路径(相对于项目根目录)
path = Path(os.getcwd()) / path
# 相对路径,转为绝对路径(相对于应用根目录)
path = Path(self.app_root) / path
if create:
try:
+5 -5
View File
@@ -49,7 +49,7 @@ class PurchaseOrderMerger:
# 修复ConfigParser对象没有get_path方法的问题
try:
# 获取输出目录
self.output_dir = config.get('Paths', 'output_folder', fallback='data/output')
self.output_dir = config.get_path('Paths', 'output_folder', fallback='data/output', create=True) if hasattr(config, 'get_path') else os.path.abspath('data/output')
# 确保目录存在
os.makedirs(self.output_dir, exist_ok=True)
@@ -96,8 +96,8 @@ class PurchaseOrderMerger:
Returns:
采购单文件路径列表
"""
# 采购单文件保存在data/result目录
result_dir = "data/result"
# 采购单文件保存在result目录
result_dir = self.config.get_path('Paths', 'result_folder', fallback='data/result', create=True) if hasattr(self.config, 'get_path') else os.path.abspath('data/result')
logger.info(f"搜索目录 {result_dir} 中的采购单Excel文件")
# 确保目录存在
@@ -354,9 +354,9 @@ class PurchaseOrderMerger:
# 采购单价(必填)- E列(4)
output_sheet.write(r, price_col, float(row['采购单价']), price_style)
# 生成输出文件名,保存到data/result目录
# 生成输出文件名,保存到result目录
timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
result_dir = "data/result"
result_dir = self.config.get_path('Paths', 'result_folder', fallback='data/result', create=True) if hasattr(self.config, 'get_path') else os.path.abspath('data/result')
os.makedirs(result_dir, exist_ok=True)
output_file = os.path.join(result_dir, f"合并采购单_{timestamp}.xls")
+3 -3
View File
@@ -52,7 +52,7 @@ class ExcelProcessor:
# 修复ConfigParser对象没有get_path方法的问题
try:
# 获取输入和输出目录
self.output_dir = config.get('Paths', 'output_folder', fallback='data/output')
self.output_dir = config.get_path('Paths', 'output_folder', fallback='data/output', create=True) if hasattr(config, 'get_path') else os.path.abspath('data/output')
self.temp_dir = config.get('Paths', 'temp_folder', fallback='data/temp')
# 获取模板文件路径
@@ -591,9 +591,9 @@ class ExcelProcessor:
logger.warning("未提取到有效商品信息")
return None
# 生成输出文件名,保存到data/result目录
# 生成输出文件名,保存到result目录
file_name = os.path.splitext(os.path.basename(file_path))[0]
result_dir = "data/result"
result_dir = self.config.get_path('Paths', 'result_folder', fallback='data/result', create=True) if hasattr(self.config, 'get_path') else os.path.abspath('data/result')
os.makedirs(result_dir, exist_ok=True)
output_file = os.path.join(result_dir, f"采购单_{file_name}.xls")
+3 -3
View File
@@ -114,9 +114,9 @@ class OCRProcessor:
# 修复ConfigParser对象没有get_path方法的问题
try:
# 获取输入和输出目录
self.input_folder = config.get('Paths', 'input_folder', fallback='data/input')
self.output_folder = config.get('Paths', 'output_folder', fallback='data/output')
self.temp_folder = config.get('Paths', 'temp_folder', fallback='data/temp')
self.input_folder = config.get_path('Paths', 'input_folder', fallback='data/input', create=True) if hasattr(config, 'get_path') else os.path.abspath('data/input')
self.output_folder = config.get_path('Paths', 'output_folder', fallback='data/output', create=True) if hasattr(config, 'get_path') else os.path.abspath('data/output')
self.temp_folder = config.get_path('Paths', 'temp_folder', fallback='data/temp', create=True) if hasattr(config, 'get_path') else os.path.abspath('data/temp')
# 确保目录存在
os.makedirs(self.input_folder, exist_ok=True)
+2 -2
View File
@@ -39,7 +39,7 @@ class TobaccoProcessor(BaseProcessor):
self.template_file = config.get('Paths', 'template_file', fallback='templates/银豹-采购单模板.xls')
# 输出目录配置
self.result_dir = Path("data/result")
self.result_dir = Path(config.get_path('Paths', 'result_folder', fallback='data/result', create=True) if hasattr(config, 'get_path') else os.path.abspath('data/result'))
self.result_dir.mkdir(exist_ok=True)
# 默认输出文件名
@@ -316,7 +316,7 @@ class TobaccoProcessor(BaseProcessor):
today_start = datetime.datetime.combine(today, datetime.time.min).timestamp()
# 查找订单明细文件
result_dir = Path("data/output")
result_dir = Path(self.config.get_path('Paths', 'output_folder', fallback='data/output') if hasattr(self.config, 'get_path') else os.path.abspath('data/output'))
if not result_dir.exists():
return None
+1 -1
View File
@@ -107,7 +107,7 @@ def create_custom_dialog(title="提示", message="", result_file=None, time_info
button_frame = tk.Frame(dialog)
button_frame.pack(pady=10)
tk.Button(button_frame, text="打开输出目录", command=lambda: os.startfile(os.path.abspath("data/output"))).pack(side=tk.LEFT, padx=5)
tk.Button(button_frame, text="打开输出目录", command=lambda: os.startfile(ConfigManager().get_path('Paths', 'output_folder', fallback='data/output', create=True))).pack(side=tk.LEFT, padx=5)
tk.Button(button_frame, text="关闭", command=dialog.destroy).pack(side=tk.LEFT, padx=5)
# 确保窗口显示在最前
+1 -1
View File
@@ -154,7 +154,7 @@ class OCRService:
# 获取文件名(不含扩展名)
base_name = os.path.splitext(os.path.basename(image_path))[0]
# 生成Excel文件路径
output_dir = self.config.get('Paths', 'output_folder', fallback='data/output')
output_dir = self.config.get_path('Paths', 'output_folder', fallback='data/output', create=True) if hasattr(self.config, 'get_path') else os.path.abspath('data/output')
excel_path = os.path.join(output_dir, f"{base_name}.xlsx")
return excel_path
+2 -2
View File
@@ -36,10 +36,10 @@ class TobaccoService:
"""
self.config = config
# 修复配置获取方式,使用fallback机制
self.output_dir = config.get('Paths', 'output_folder', fallback='data/output')
self.output_dir = config.get_path('Paths', 'output_folder', fallback='data/output', create=True) if hasattr(config, 'get_path') else os.path.abspath('data/output')
self.template_file = config.get('Paths', 'template_file', fallback='templates/银豹-采购单模板.xls')
# 将烟草订单保存到result目录
result_dir = "data/result"
result_dir = config.get_path('Paths', 'result_folder', fallback='data/result', create=True) if hasattr(config, 'get_path') else os.path.abspath('data/result')
os.makedirs(result_dir, exist_ok=True)
self.output_file = os.path.join(result_dir, '银豹采购单_烟草公司.xls')
+5 -3
View File
@@ -63,9 +63,11 @@ def run_command_with_logging(command, log_widget, status_bar=None, on_complete=N
env["OCR_INPUT_DIR"] = cfg.get_path('Paths', 'input_folder', fallback='data/input', create=True)
env["OCR_TEMP_DIR"] = cfg.get_path('Paths', 'temp_folder', fallback='data/temp', create=True)
except Exception:
env["OCR_OUTPUT_DIR"] = os.path.abspath("data/output")
env["OCR_INPUT_DIR"] = os.path.abspath("data/input")
env["OCR_TEMP_DIR"] = os.path.abspath("data/temp")
# 回退:使用 exe/脚本所在目录
app_root = os.path.dirname(sys.executable) if getattr(sys, 'frozen', False) else os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
env["OCR_OUTPUT_DIR"] = os.path.join(app_root, "data", "output")
env["OCR_INPUT_DIR"] = os.path.join(app_root, "data", "input")
env["OCR_TEMP_DIR"] = os.path.join(app_root, "data", "temp")
env["OCR_LOG_LEVEL"] = "DEBUG"
try:
+2 -2
View File
@@ -34,8 +34,8 @@ def get_error_suggestion(message: str) -> Optional[str]:
return '降低识别频率或稍后重试'
if '模板文件不存在' in msg or ('no such file' in msg and '模板' in msg):
return '在系统设置中选择正确的模板文件路径'
if '没有找到采购单' in msg or '未在 data/result 目录下找到采购单' in msg:
return '确认data/result目录内存在采购单文件'
if '没有找到采购单' in msg or '未在' in msg and '找到采购单' in msg:
return '确认result目录内存在采购单文件'
if 'permission denied' in msg:
return '以管理员权限运行或更改目录写入权限'
return None
+20 -22
View File
@@ -35,11 +35,11 @@ def ensure_directories():
"""确保必要的目录结构存在"""
config = ConfigManager()
directories = [
config.get('Paths', 'input_folder', fallback='data/input'),
config.get('Paths', 'output_folder', fallback='data/output'),
'data/result',
config.get('Paths', 'temp_folder', fallback='data/temp'),
'logs'
config.get_path('Paths', 'input_folder', fallback='data/input', create=True),
config.get_path('Paths', 'output_folder', fallback='data/output', create=True),
config.get_path('Paths', 'result_folder', fallback='data/result', create=True),
config.get_path('Paths', 'temp_folder', fallback='data/temp', create=True),
os.path.join(config.app_root, 'logs')
]
for directory in directories:
if not os.path.exists(directory):
@@ -52,8 +52,8 @@ def clean_cache(log_widget):
from .command_runner import set_running_task
try:
config = ConfigManager()
processed_record = config.get('Paths', 'processed_record', fallback='data/processed_files.json')
output_folder = config.get('Paths', 'output_folder', fallback='data/output')
processed_record = config.get_path('Paths', 'processed_record', fallback='data/processed_files.json')
output_folder = config.get_path('Paths', 'output_folder', fallback='data/output')
cache_files = [
processed_record,
os.path.join(output_folder, "processed_files.json"),
@@ -65,7 +65,7 @@ def clean_cache(log_widget):
os.remove(cache_file)
add_to_log(log_widget, f"已清除缓存文件: {cache_file}\n", "success")
temp_dir = os.path.join("data/temp")
temp_dir = config.get_path('Paths', 'temp_folder', fallback='data/temp')
if os.path.exists(temp_dir):
for file in os.listdir(temp_dir):
file_path = os.path.join(temp_dir, file)
@@ -76,7 +76,7 @@ def clean_cache(log_widget):
except Exception as e:
add_to_log(log_widget, f"清除文件时出错: {file_path}, 错误: {str(e)}\n", "error")
log_dir = "logs"
log_dir = os.path.join(config.app_root, 'logs')
if os.path.exists(log_dir):
for file in os.listdir(log_dir):
if file.endswith(".active"):
@@ -98,22 +98,18 @@ def clean_cache(log_widget):
def open_result_directory():
try:
result_dir = os.path.abspath("data/result")
if not os.path.exists(result_dir):
os.makedirs(result_dir, exist_ok=True)
config = ConfigManager()
result_dir = config.get_path('Paths', 'result_folder', fallback='data/result', create=True)
os.startfile(result_dir)
except Exception as e:
messagebox.showerror("错误", f"无法打开结果目录: {str(e)}")
def _open_directory_from_settings(settings_key, default_path, label):
"""通用的从用户设置读取路径并打开目录"""
from .user_settings import load_user_settings
def _open_directory_from_settings(config_key, default_path, label):
"""通用的从置读取路径并打开目录"""
try:
s = load_user_settings()
path = os.path.abspath(s.get(settings_key, default_path))
if not os.path.exists(path):
os.makedirs(path, exist_ok=True)
config = ConfigManager()
path = config.get_path('Paths', config_key, fallback=default_path, create=True)
os.startfile(path)
except Exception as e:
messagebox.showerror("错误", f"无法打开{label}: {str(e)}")
@@ -138,9 +134,10 @@ def clean_data_files(log_widget):
add_to_log(log_widget, "操作已取消\n", "info")
return
config = ConfigManager()
files_cleaned = 0
input_dir = "data/input"
input_dir = config.get_path('Paths', 'input_folder', fallback='data/input')
if os.path.exists(input_dir):
for file in os.listdir(input_dir):
file_path = os.path.join(input_dir, file)
@@ -149,7 +146,7 @@ def clean_data_files(log_widget):
files_cleaned += 1
add_to_log(log_widget, "已清理input目录\n", "info")
output_dir = "data/output"
output_dir = config.get_path('Paths', 'output_folder', fallback='data/output')
if os.path.exists(output_dir):
for file in os.listdir(output_dir):
file_path = os.path.join(output_dir, file)
@@ -170,8 +167,9 @@ def clean_result_files(log_widget):
if not messagebox.askyesno("确认清理", "确定要清理result目录的文件吗?这将删除所有已生成的采购单文件。"):
add_to_log(log_widget, "操作已取消\n", "info")
return
config = ConfigManager()
count = 0
result_dir = "data/result"
result_dir = config.get_path('Paths', 'result_folder', fallback='data/result')
if os.path.exists(result_dir):
for file in os.listdir(result_dir):
file_path = os.path.join(result_dir, file)
+5 -4
View File
@@ -238,8 +238,8 @@ def _create_right_panel(content_frame, theme, log_text, root):
tk.Frame(tools_buttons_frame, bg=theme["card_bg"]).pack(fill=tk.X, pady=3)
create_modern_button(tools_buttons_frame, "打开结果目录", lambda: open_result_directory(), "primary", px_width=132, px_height=32).pack(anchor='w', pady=3)
create_modern_button(tools_buttons_frame, "打开输出目录", lambda: os.startfile(os.path.abspath("data/output")), "primary", px_width=132, px_height=32).pack(anchor='w', pady=3)
create_modern_button(tools_buttons_frame, "打开输入目录", lambda: os.startfile(os.path.abspath("data/input")), "primary", px_width=132, px_height=32).pack(anchor='w', pady=3)
create_modern_button(tools_buttons_frame, "打开输出目录", lambda: os.startfile(ConfigManager().get_path('Paths', 'output_folder', fallback='data/output', create=True)), "primary", px_width=132, px_height=32).pack(anchor='w', pady=3)
create_modern_button(tools_buttons_frame, "打开输入目录", lambda: os.startfile(ConfigManager().get_path('Paths', 'input_folder', fallback='data/input', create=True)), "primary", px_width=132, px_height=32).pack(anchor='w', pady=3)
create_modern_button(tools_buttons_frame, "合并订单", lambda: merge_orders_with_status(log_text, StatusBar(root)), "primary", px_width=132, px_height=32).pack(anchor='w', pady=3)
create_modern_button(tools_buttons_frame, "清除缓存", lambda: clean_cache(log_text), "primary", px_width=132, px_height=32).pack(anchor='w', pady=3)
create_modern_button(tools_buttons_frame, "清理input/out文件", lambda: clean_data_files(log_text), "primary", px_width=132, px_height=32).pack(anchor='w', pady=3)
@@ -433,8 +433,9 @@ def _create_log_panel(mid_container, theme):
add_to_log(log_text, "• 批量处理订单:批量处理多个订单文件\n", "info")
add_to_log(log_text, "• 处理烟草订单:专门处理烟草类订单\n", "info")
add_to_log(log_text, "• 合并订单:将多个订单合并为一个文件\n\n", "info")
add_to_log(log_text, "请将需要处理的图片文件放入 data/input 目录中。\n", "warning")
add_to_log(log_text, "OCR识别结果保存在 data/output 目录,处理完成的订单保存在 result 目录中。\n\n", "warning")
cfg = ConfigManager()
add_to_log(log_text, f"请将需要处理的图片文件放入 {cfg.get_path('Paths', 'input_folder', fallback='data/input')} 目录中。\n", "warning")
add_to_log(log_text, f"OCR识别结果保存在 {cfg.get_path('Paths', 'output_folder', fallback='data/output')} 目录,处理完成的订单保存在 {cfg.get_path('Paths', 'result_folder', fallback='data/result')} 目录中。\n\n", "warning")
add_to_log(log_text, "=" * 50 + "\n\n", "separator")
return log_text
+16 -10
View File
@@ -11,10 +11,16 @@ from tkinter import messagebox, scrolledtext
from .theme import THEMES, get_theme_mode, apply_theme
from .ui_widgets import center_window
from app.core.utils.file_utils import format_file_size
from app.config.settings import ConfigManager
TOBACCO_PREVIEW_WINDOW = None
def _get_output_dir():
"""获取输出目录的绝对路径"""
return ConfigManager().get_path('Paths', 'output_folder', fallback='data/output', create=True)
def show_result_preview(command, output):
"""显示处理结果预览"""
if "ocr" in command:
@@ -26,7 +32,7 @@ def show_result_preview(command, output):
elif "pipeline" in command:
show_pipeline_result_preview(output)
else:
messagebox.showinfo("处理完成", "操作已成功完成!\n请在data/output目录查看结果。")
messagebox.showinfo("处理完成", f"操作已成功完成!\n请在{_get_output_dir()}目录查看结果。")
def show_ocr_result_preview(output):
@@ -68,10 +74,10 @@ def show_ocr_result_preview(output):
button_frame = tk.Frame(preview)
button_frame.pack(pady=10)
tk.Button(button_frame, text="查看输出文件", command=lambda: os.startfile(os.path.abspath("data/output"))).pack(side=tk.LEFT, padx=10)
tk.Button(button_frame, text="查看输出文件", command=lambda: os.startfile(_get_output_dir())).pack(side=tk.LEFT, padx=10)
tk.Button(button_frame, text="关闭", command=preview.destroy).pack(side=tk.LEFT, padx=10)
else:
messagebox.showinfo("OCR处理完成", "OCR处理已完成,请在data/output目录查看结果。")
messagebox.showinfo("OCR处理完成", f"OCR处理已完成,请在{_get_output_dir()}目录查看结果。")
def show_excel_result_preview(output):
@@ -120,7 +126,7 @@ def show_excel_result_preview(output):
tk.Button(button_frame, text="打开所在文件夹", command=lambda: os.startfile(os.path.dirname(output_file))).pack(side=tk.LEFT, padx=5)
tk.Button(button_frame, text="关闭", command=preview.destroy).pack(side=tk.LEFT, padx=5)
else:
messagebox.showinfo("Excel处理完成", "Excel处理已完成,请在data/output目录查看结果。")
messagebox.showinfo("Excel处理完成", f"Excel处理已完成,请在{_get_output_dir()}目录查看结果。")
def show_merge_result_preview(output):
@@ -159,7 +165,7 @@ def show_merge_result_preview(output):
tk.Button(button_frame, text="打开所在文件夹", command=lambda: os.startfile(os.path.dirname(output_file))).pack(side=tk.LEFT, padx=10)
tk.Button(button_frame, text="关闭", command=preview.destroy).pack(side=tk.LEFT, padx=10)
else:
messagebox.showinfo("采购单合并完成", "采购单合并已完成,请在data/output目录查看结果。")
messagebox.showinfo("采购单合并完成", f"采购单合并已完成,请在{_get_output_dir()}目录查看结果。")
def show_pipeline_result_preview(output):
@@ -250,7 +256,7 @@ def show_pipeline_result_preview(output):
tk.Button(button_frame, text="打开Excel文件", command=lambda: os.startfile(output_file)).pack(side=tk.LEFT, padx=10)
else:
if excel_match or no_files_match or single_file_match:
output_dir = os.path.abspath("data/output")
output_dir = _get_output_dir()
excel_files = [f for f in os.listdir(output_dir) if f.startswith('采购单_') and (f.endswith('.xls') or f.endswith('.xlsx'))]
if excel_files:
excel_files.sort(key=lambda x: os.path.getmtime(os.path.join(output_dir, x)), reverse=True)
@@ -258,7 +264,7 @@ def show_pipeline_result_preview(output):
tk.Button(button_frame, text="打开最新Excel文件",
command=lambda: os.startfile(latest_file)).pack(side=tk.LEFT, padx=10)
tk.Button(button_frame, text="查看输出文件夹", command=lambda: os.startfile(os.path.abspath("data/output"))).pack(side=tk.LEFT, padx=10)
tk.Button(button_frame, text="查看输出文件夹", command=lambda: os.startfile(_get_output_dir())).pack(side=tk.LEFT, padx=10)
tk.Button(button_frame, text="关闭", command=preview.destroy).pack(side=tk.LEFT, padx=10)
@@ -299,7 +305,7 @@ def show_tobacco_result_preview(returncode, output):
items_count = int(items_match.group(1).strip())
if not result_file or not os.path.exists(result_file):
default_path = os.path.abspath("data/output/银豹采购单_烟草公司.xls")
default_path = os.path.join(_get_output_dir(), "银豹采购单_烟草公司.xls")
if os.path.exists(default_path):
result_file = default_path
@@ -353,11 +359,11 @@ def show_tobacco_result_preview(returncode, output):
tk.Button(button_frame, text="关闭", command=_close_preview).pack(side=tk.LEFT, padx=5)
else:
tk.Label(result_frame, text="未找到输出文件", font=("Arial", 12)).pack(anchor=tk.W, padx=20, pady=5)
tk.Label(result_frame, text="请检查data/output目录", font=("Arial", 12, "bold"), fg="#dc3545").pack(pady=10)
tk.Label(result_frame, text=f"请检查{_get_output_dir()}目录", font=("Arial", 12, "bold"), fg="#dc3545").pack(pady=10)
button_frame = tk.Frame(preview)
button_frame.pack(pady=10)
tk.Button(button_frame, text="打开输出目录", command=lambda: os.startfile(os.path.abspath("data/output"))).pack(side=tk.LEFT, padx=5)
tk.Button(button_frame, text="打开输出目录", command=lambda: os.startfile(_get_output_dir())).pack(side=tk.LEFT, padx=5)
tk.Button(button_frame, text="关闭", command=_close_preview).pack(side=tk.LEFT, padx=5)
preview.lift()
+3 -1
View File
@@ -9,6 +9,7 @@ import tkinter as tk
from typing import Dict, List, Any
from app.core.utils.log_utils import get_logger
from app.config.settings import ConfigManager
logger = get_logger(__name__)
@@ -54,7 +55,8 @@ def get_recent_files() -> List[str]:
kept = [p for p in items if _allowed(p)]
if not kept:
candidates = []
for d in ['data/output', 'data/result']:
cfg = ConfigManager()
for d in [cfg.get_path('Paths', 'output_folder', fallback='data/output'), cfg.get_path('Paths', 'result_folder', fallback='data/result')]:
try:
if os.path.exists(d):
for name in os.listdir(d):