在Mac上使用Pyinstaller创建了一个应用程序,该应用程序无法运行,但shell文件可以运行。为什么?

问题描述 投票:0回答:1

我正在创建一个为我的学校生成时间表的应用程序。这是它的Python代码:

import tkinter as tk
from tkinter import ttk
import os
import json
import logging
import datetime
import sys

logging.basicConfig(level=logging.DEBUG, filename='app.log', filemode='w',
                    format='%(name)s - %(levelname)s - %(message)s')

if getattr(sys, 'frozen', False):
    application_path = os.path.dirname(sys.executable)
else:
    application_path = os.path.dirname(__file__)
  
PREFERENCES_FILE = os.path.join(application_path, "user_preferences.json")

def save_preferences(data):
    try:
        with open(PREFERENCES_FILE, 'w') as f:
            json.dump(data, f)
        logging.info("Preferences saved successfully.")
    except Exception as e:
        logging.error(f"Failed to save preferences: {e}")
      
def load_preferences():
    try:
        if os.path.exists(PREFERENCES_FILE):
            with open(PREFERENCES_FILE, 'r') as f:
                return json.load(f)
    except Exception as e:
        logging.error(f"Error reading preferences: {e}")
    return None

def delete_preferences():
    try:
        if os.path.exists(PREFERENCES_FILE):
            os.remove(PREFERENCES_FILE)
            logging.info("Preferences deleted successfully.")
    except Exception as e:
        logging.error(f"Failed to delete preferences: {e}")
      
def show_schedule(day, preferences):
    schedule = preferences['schedule']
    day_schedule = schedule.get(day, [])
    schedule_text = f"Schedule for {day}:\n"
    for time_range, subject_key in day_schedule:
        subject = preferences['subjects'].get(subject_key, "Free")
        schedule_text += f"{time_range} - {subject}\n"
    schedule_label.config(text=schedule_text)
  
def setup_preferences():
    def save_and_close():
        subjects = {
            'MESH1': mesh1_var.get(),
            'MESH2': mesh2_var.get(),
            'MESH3': mesh3_var.get(),
            'MESH4': mesh4_var.get(),
            'WL': wl_var.get(),
            'WELLNESS': 'Wellness',
            'ELECTIVE1': elective1_entry.get(),
            'ELECTIVE2': elective2_entry.get(),
            'CLUB': club_entry.get(),
            'GEOMETRY': 'Geometry' if geometry_var.get() else None,
            'RECESS': 'Recess',
            'LUNCH': 'Lunch',
            'ACADEMIC_COACHING': 'Academic Coaching',
            'ADVISORY': 'Advisory'
        }
        preferences = {
            'subjects': subjects,
            'schedule': load_default_schedule(geometry_var.get())
        }
        save_preferences(preferences)
        setup_root.destroy()
        main_app()
      
    setup_root = tk.Tk()
    setup_root.title("Setup Preferences")
  
    mesh_options = ["Math", "English", "Science", "History"]
    wl_options = ["Spanish", "French", "FOL"]
    mesh1_var, mesh2_var, mesh3_var, mesh4_var, wl_var = tk.StringVar(), tk.StringVar(), tk.StringVar(), tk.StringVar(), tk.StringVar()
    geometry_var = tk.BooleanVar()
  
    ttk.Label(setup_root, text="Select MESH1:").pack()
    ttk.Combobox(setup_root, textvariable=mesh1_var, values=mesh_options).pack()
    ttk.Label(setup_root, text="Select MESH2:").pack()
    ttk.Combobox(setup_root, textvariable=mesh2_var, values=mesh_options).pack()
    ttk.Label(setup_root, text="Select MESH3:").pack()
    ttk.Combobox(setup_root, textvariable=mesh3_var, values=mesh_options).pack()
    ttk.Label(setup_root, text="Select MESH4:").pack()
    ttk.Combobox(setup_root, textvariable=mesh4_var, values=mesh_options).pack()
    ttk.Label(setup_root, text="Select WL:").pack()
    ttk.Combobox(setup_root, textvariable=wl_var, values=wl_options).pack()
  
    ttk.Checkbutton(setup_root, text="Include Geometry", variable=geometry_var).pack()
  
    ttk.Label(setup_root, text="Enter AM ICE:").pack()
    elective1_entry = ttk.Entry(setup_root)
    elective1_entry.pack()
    ttk.Label(setup_root, text="Enter PM ICE:").pack()
    elective2_entry = ttk.Entry(setup_root)
    elective2_entry.pack()
    ttk.Label(setup_root, text="Enter Club:").pack()
    club_entry = ttk.Entry(setup_root)
    club_entry.pack()
  
    ttk.Button(setup_root, text="Save and Start", command=save_and_close).pack(pady=10)
    setup_root.mainloop()
  
def load_default_schedule(include_geometry):
    today = datetime.datetime.today().weekday()  # Monday is 0 and Sunday is 6
    geometry_days = [0, 2, 4]  # Monday, Wednesday, Friday
  
    schedule = {
        'A': [("8:10-8:30", "ADVISORY"), ("8:30-9:20", "CLUB"), ("9:20-10:10", "MESH1"),
              ("10:10-10:30", "RECESS"), ("10:30-11:20", "MESH3"), ("11:20-12:10", "MESH2"),
              ("12:10-12:40", "LUNCH"), ("12:40-1:30", "WL"), ("1:30-2:20", "MESH4"), ("2:20-3:10", "ELECTIVE2")],
        'B': [("8:10-8:30", "ADVISORY"), ("8:30-9:20", "ELECTIVE1"), ("9:20-10:10", "WL"),
              ("10:10-10:30", "RECESS"), ("10:30-11:20", "MESH2"), ("11:20-12:10", "MESH3"),
              ("12:10-12:40", "LUNCH"), ("12:40-1:30", "MESH4"), ("1:30-2:20", "MESH1"), ("2:20-3:10", "ELECTIVE2")],
        'C': [("8:10-8:30", "ADVISORY"), ("8:30-9:20", "ACADEMIC_COACHING"), ("9:20-10:10", "MESH2"),
              ("10:10-10:30", "RECESS"), ("10:30-11:20", "MESH4"), ("11:20-12:10", "MESH1"),
              ("12:10-12:40", "LUNCH"), ("12:40-1:30", "WL"), ("1:30-2:20", "MESH3"), ("2:20-3:10", "ELECTIVE2")],
        'D': [("8:10-8:30", "ADVISORY"), ("8:30-9:20", "ELECTIVE1"), ("9:20-10:10", "WL"),
              ("10:10-10:30", "RECESS"), ("10:30-11:20", "MESH4"), ("11:20-12:10", "MESH1"),
              ("12:10-12:40", "LUNCH"), ("12:40-1:30", "MESH3"), ("1:30-2:20", "MESH2"), ("2:20-3:10", "ACADEMIC_COACHING")],
        'E': [("8:10-8:30", "ADVISORY"), ("8:30-9:20", "ELECTIVE1"), ("9:20-10:10", "MESH1"),
              ("10:10-10:30", "RECESS"), ("10:30-11:20", "MESH3"), ("11:20-12:10", "MESH2"),
              ("12:10-12:40", "LUNCH"), ("12:40-1:30", "WELLNESS"), ("1:30-2:20", "MESH4"), ("2:20-3:10", "ELECTIVE2")],
        'F': [("8:10-8:30", "ADVISORY"), ("8:30-9:20", "ELECTIVE1"), ("9:20-10:10", "WL"),
              ("10:10-10:30", "RECESS"), ("10:30-11:20", "MESH2"), ("11:20-12:10", "MESH3"),
              ("12:10-12:40", "LUNCH"), ("12:40-1:30", "MESH4"), ("1:30-2:20", "MESH1"), ("2:20-3:10", "ACADEMIC_COACHING")]
    }
  
    if include_geometry and today in geometry_days:
        geometry_class = ("7:00-8:00", "GEOMETRY")
        for key in schedule:
            schedule[key].insert(0, geometry_class)
          
    return schedule

def main_app():
    preferences = load_preferences()
    if not preferences:
        setup_preferences()
        return
  
    root = tk.Tk()
    root.title("School Schedule")
  
    day_var = tk.StringVar(value='A')
    day_dropdown = ttk.Combobox(root, textvariable=day_var, values=list('ABCDEF'))
    day_dropdown.pack(pady=10)
  
    show_button = ttk.Button(root, text="Show Schedule", command=lambda: show_schedule(day_var.get(), preferences))
    show_button.pack(pady=5)
  
    reset_button = ttk.Button(root, text="Reset Preferences", command=lambda: [delete_preferences(), root.destroy(), setup_preferences()])
    reset_button.pack(pady=5)
  
    global schedule_label
    schedule_label = tk.Label(root, text="", justify=tk.LEFT)
    schedule_label.pack(pady=10)
  
    root.mainloop()
  
if __name__ == "__main__":
    main_app()
  

我尝试使用以下命令在我的 Mac 上创建程序:

pyinstaller --windowed --onefile --icon=/Users/jacob/\ icon.iconset/857457.icns --name="School Schedule App" /Users/jacob/School_Schedule_App.py

当我尝试双击打开该应用程序时,没有任何反应。但是,如果我进入包内容,然后进入 MacOS 文件夹,运行 shell 脚本将打开应用程序并使其正常运行。为什么会这样,如何才能正常打开应用程序就可以运行?

谢谢您,如果您有任何后续问题,请告诉我,我会尽力回答。

python macos pyinstaller .app
1个回答
0
投票

应用程序的日志目录应使用完整目录: logging.basicConfig(level=logging.DEBUG, filename='app.log', filemode='w', 格式='%(名称)s - %(级别名称)s - %(消息)s')

====》

logging.basicConfig(level=logging.DEBUG, filename='/Users/hodge/Desktop/code_demo/python/build/app.log', filemode='w', 格式='%(名称)s - %(级别名称)s - %(消息)s')

© www.soinside.com 2019 - 2024. All rights reserved.