IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Déploiement/Installation Python Discussion :

Partager un programme Python


Sujet :

Déploiement/Installation Python

  1. #1
    Rédacteur/Modérateur
    Avatar de troumad
    Homme Profil pro
    Enseignant
    Inscrit en
    Novembre 2003
    Messages
    5 613
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 57
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Enseignant
    Secteur : Enseignement

    Informations forums :
    Inscription : Novembre 2003
    Messages : 5 613
    Par défaut Partager un programme Python
    Bonsoir

    Python étant de plus en plus en vogue, et comme je l'utilise depuis dans mon enseignement avec les bibliothèques mathématiques avec jupyther, suite à une demande j'ai développé un programme python. Un bon entrainement poujr mon travail.
    Quand je développais un programme en C, un coup de cross-compilation et je pouvais le passer aux (malheureux) utilisateurs de windows. Sous Linux, pour lancer mon code python, c'est très simple, en ligne de commande, j'exécute mon script grâce à son entête ou je clique sur le fichier avec un explorateur de fichiers.
    Mais, que faire pour le passer aux utilisateur de windows ? Leur dire d'installer spyder ? Jupyther ? Il n'est pas possible de cliquer sur un code en python et que l'explorateur de fichiers exécute automatiquement le fichiert avec l'interpréteur python ?

    Si vous avez envie, voici mon code en PJ.
    Fichiers attachés Fichiers attachés
    Modérateur Mageia/Mandriva Linux
    Amicalement VOOotre
    Troumad Alias Bernard SIAUD à découvrir sur http://troumad.org
    Mes tutoriels : xrandr, algorigramme et C, xml et gtk...

  2. #2
    Expert confirmé Avatar de papajoker
    Homme Profil pro
    Développeur Web
    Inscrit en
    Septembre 2013
    Messages
    2 330
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Nièvre (Bourgogne)

    Informations professionnelles :
    Activité : Développeur Web
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Septembre 2013
    Messages : 2 330
    Par défaut
    bonjour

    Attention aux dépendances ...

    chez moi (archlinux), il faut installer python-pillow, autre linux, autre paquet ?

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    gi.require_version("Gtk", "3.0")
    Il faut donc aussi gtk ... attention, a ma connaissance, il n'existe pas de librairie gtk directement/facilement disponible sous windows.
    Sous windows : tk et Qt, aucun problème. tk: pas de framework à installer et le framework Qt est disponible.

    A la vue de la fenêtre principale relativement simple, tk est ici une bonne alternative à gtk pour un portage multi os.

    mon enseignement
    désolé, mais ce code python n'est certainement pas un "modèle" ...
    utilisation de gtk non objet (comme tk)
    utilisations de global
    fonctions interminables
    mélange du gui et du code travail


    --------------

    GUI

    pourquoi le bouton "calculer" n'est pas à côté de "fermer", il m'a fallu du temps pour le trouver

  3. #3
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 790
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 790
    Par défaut
    Citation Envoyé par troumad Voir le message
    Il n'est pas possible de cliquer sur un code en python et que l'explorateur de fichiers exécute automatiquement le fichiert avec l'interpréteur python ?
    Il existe des outils de packaging tels que cx_freeze ou pyinstaller pour emballer interpréteurs et bibliothèques utilisées permettant d'utiliser le script sans avoir à tout installer: le tout étant diffusé sous la forme d'un exécutable.

    L'autre alternative est d'installer au moins python et l'application via pip en renseignant les dépendances à installer dans le fichier requirements.txt. Ce qui permettra leur installation "automatique" (mais ça ne va installer que les bibliothèques python probablement pas un GTK+).

    Ceci dit vous utilisez Jupyter et vos applications pourraient être des "notebooks" et se déployer spécifiquement (c'est autre chose que des scripts python).... mais c'est un domaine que je n'ai pas exploré.

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  4. #4
    Rédacteur/Modérateur
    Avatar de troumad
    Homme Profil pro
    Enseignant
    Inscrit en
    Novembre 2003
    Messages
    5 613
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 57
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Enseignant
    Secteur : Enseignement

    Informations forums :
    Inscription : Novembre 2003
    Messages : 5 613
    Par défaut
    Je suis en train de regarder tk.
    Mon but est de passer l'application à des non informaticiens. Donc, parler de jupyter ou autre n'est pas envisageable.
    Modérateur Mageia/Mandriva Linux
    Amicalement VOOotre
    Troumad Alias Bernard SIAUD à découvrir sur http://troumad.org
    Mes tutoriels : xrandr, algorigramme et C, xml et gtk...

  5. #5
    Membre Expert
    Homme Profil pro
    Enseignant
    Inscrit en
    Juin 2013
    Messages
    1 627
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Enseignant
    Secteur : Enseignement

    Informations forums :
    Inscription : Juin 2013
    Messages : 1 627
    Par défaut
    Pas trrop compris à quoi servait ce programme : l'intérêt des cartes ?

    Sinon, j'ai mis beaucoup de temps à trouver "Calculer".
    Proposition : Quand on change la couleur : le fond ou la police pourrait également changer de couleur.

  6. #6
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 790
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Manche (Basse Normandie)

    Informations professionnelles :
    Activité : Architecte technique retraité
    Secteur : Industrie

    Informations forums :
    Inscription : Juin 2008
    Messages : 21 790
    Par défaut
    Citation Envoyé par troumad Voir le message
    Je suis en train de regarder tk.
    Mon but est de passer l'application à des non informaticiens. Donc, parler de jupyter ou autre n'est pas envisageable.
    Alors vous devrez regarder et apprendre à utiliser un cx_freeze ou un pyinstaller... et vous devriez pouvoir garder gtk.

    - W
    Architectures post-modernes.
    Python sur DVP c'est aussi des FAQs, des cours et tutoriels

  7. #7
    Expert confirmé
    Avatar de fred1599
    Homme Profil pro
    Lead Dev Python
    Inscrit en
    Juillet 2006
    Messages
    4 754
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : Lead Dev Python
    Secteur : Arts - Culture

    Informations forums :
    Inscription : Juillet 2006
    Messages : 4 754
    Par défaut
    Hello,

    Un bon entrainement pour mon travail.
    Vous pourriez vous concentrez sur des bonnes pratiques,
    1. retrait des variables globales
    2. faire attention aux lignes trop longues ( > 100 )
    3. mettre des annotations de type (évite les docstrings à rallonge)
    4. découper un peu mieux votre code
    5. variables, fonctions, ... en anglais


    Voici un code que je vous propose pour démarrer d'une manière plus solide... Il vous resterait à séparer les responsabilités afin de rendre le code plus lisible.
    Il me semble que je gagne 3x en nombre de lignes.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
     
    import datetime
     
    import math
    import traceback
    from typing import Any
     
    from PIL import Image, ImageDraw, ImageFont, PngImagePlugin
    import gi
     
    gi.require_version("Gtk", "3.0")
    from gi.repository import Gtk  # type: ignore
     
     
    # -------------------- Global Variables -------------------- #
     
    grid_width: int = 10
    grid_height: int = 10
    side_length: float = 30.0
    line_color: tuple[int, int, int, int] = (192, 192, 192, 255)
    text_color: tuple[int, int, int, int] = (0, 0, 0, 255)
    line_thickness: int = 2
    output_filename: str = "hex_grid"
    default_orientation: str = "pointy"
    default_font_path: str = "arial.ttf"
    default_font_size: int = 12
     
    # -------------------- Utility Functions -------------------- #
     
    def calculate_pointy_top_hex_points(side: float) -> list[tuple[float, float]]:
        """Calculate the vertices of a pointy-top hexagon relative to center (0,0)."""
        return [
            (side * math.cos(math.radians(angle)), side * math.sin(math.radians(angle)))
            for angle in [30, 90, 150, 210, 270, 330]
        ]
     
     
    def calculate_flat_top_hex_points(side: float) -> list[tuple[float, float]]:
        """Calculate the vertices of a flat-top hexagon relative to center (0,0)."""
        return [
            (side * math.cos(math.radians(angle)), side * math.sin(math.radians(angle)))
            for angle in [0, 60, 120, 180, 240, 300]
        ]
     
     
    def generate_grid(
        g_width: int,
        g_height: int,
        s_length: float,
        l_color: tuple[int, int, int, int],
        t_color: tuple[int, int, int, int],
        l_thickness: int,
        orientation: str,
        draw_coords: bool = True,
    ) -> Image.Image:
        """Generate a hexagonal grid image."""
        hex_points: list[tuple[float, float]]
        x_spacing: float
        y_spacing: float
     
        if orientation == default_orientation:
            hex_points = calculate_pointy_top_hex_points(s_length)
            x_spacing = 1.5 * s_length
            y_spacing = math.sqrt(3) * s_length
        elif orientation == "flat":
            hex_points = calculate_flat_top_hex_points(s_length)
            x_spacing = math.sqrt(3) * s_length
            y_spacing = 1.5 * s_length
        else:
            raise ValueError("Invalid orientation. Choose 'pointy' or 'flat'.")
     
        margin: int = int(s_length)
        image_width: int = int(
            (g_width * x_spacing)
            + (0.5 * x_spacing if orientation == "flat" else 0)
            + 2 * margin
        )
        image_height: int = int(
            (g_height * y_spacing)
            + (0.5 * y_spacing if orientation == default_orientation else 0)
            + 2 * margin
        )
     
        img: Image.Image = Image.new(
            "RGBA", (image_width, image_height), (255, 255, 255, 0)
        )
        draw: Any = ImageDraw.Draw(img)
     
        for row in range(g_height):
            for col in range(g_width):
                center_x: float = col * x_spacing + margin
                center_y: float = row * y_spacing + margin
     
                if orientation == default_orientation and col % 2 == 1:
                    center_y += y_spacing / 2
                elif orientation == "flat" and row % 2 == 1:
                    center_x += x_spacing / 2
     
                hex_coords: list[tuple[float, float]] = [
                    (x + center_x, y + center_y) for x, y in hex_points
                ]
                draw.polygon(hex_coords, outline=l_color, width=l_thickness)
     
                if draw_coords:
                    draw_text(
                        draw,
                        f"{col},{row}",
                        (center_x, center_y),
                        t_color,
                        default_font_size,
                    )
     
        return img
     
     
    def draw_text(
        draw: Any,
        text: str,
        position: tuple[float, float],
        color: tuple[int, int, int, int],
        font_size: int,
    ) -> None:
        """Draw text centered at a given position."""
        font: ImageFont.FreeTypeFont | ImageFont.ImageFont
        try:
            font = ImageFont.truetype(default_font_path, size=font_size)
        except IOError:
            print(
                f"Avertissement : Police '{default_font_path}'"
                " non trouvée, utilisation de la police par défaut."
            )
            font = ImageFont.load_default()
     
        draw.text(position, text, fill=color, font=font, anchor="mm")
     
     
    def save_image_with_metadata(
        image: Image.Image, filename: str, metadata_dict: dict[str, Any]
    ) -> str:
        """Save the generated grid with metadata from a dictionary."""
        png_info = PngImagePlugin.PngInfo()
        for key, value in metadata_dict.items():
            png_info.add_text(str(key), str(value))
     
        if not filename.lower().endswith(".png"):
            filename += ".png"
     
        try:
            image.save(filename, "PNG", pnginfo=png_info)
            return f"Grid saved as {filename}"
        except Exception as e:
            raise IOError(f"Failed to save image {filename}: {e}") from e
     
    # -------------------- GTK Interface Functions -------------------- #
     
    def on_generate_clicked(_button: Any | None) -> None:
        """Generate the grid when the button is clicked."""
        try:
            current_grid_width: int = int(entry_grid_width.get_text())
            current_grid_height: int = int(entry_grid_height.get_text())
            current_side_length: float = float(entry_side_length.get_text())
            current_output_filename: str = entry_output_filename.get_text()
            current_orientation: str = default_orientation if radio_pointy_top.get_active() else "flat"
            current_line_color: tuple[int, int, int, int] = line_color
            current_text_color: tuple[int, int, int, int] = text_color
            current_line_thickness: int = line_thickness
     
            if (
                current_grid_width <= 0
                or current_grid_height <= 0
                or current_side_length <= 0
            ):
                raise ValueError("Dimensions and side length must be positive.")
            if not current_output_filename:
                raise ValueError("Output filename cannot be empty.")
     
            img: Image.Image = generate_grid(
                g_width=current_grid_width,
                g_height=current_grid_height,
                s_length=current_side_length,
                l_color=current_line_color,
                t_color=current_text_color,
                l_thickness=current_line_thickness,
                orientation=current_orientation,
                draw_coords=True,
            )
     
            metadata: dict[str, Any] = {
                "grid_width": current_grid_width,
                "grid_height": current_grid_height,
                "side_length": current_side_length,
                "line_color": str(current_line_color),
                "text_color": str(current_text_color),
                "line_thickness": current_line_thickness,
                "orientation": current_orientation,
                "generation_date": datetime.datetime.now().isoformat(),
            }
     
            success_message: str = save_image_with_metadata(
                img, current_output_filename, metadata
            )
            dialog_success(success_message)
     
        except ValueError as ve:
            dialog_error(f"Invalid Input: {ve}")
        except IOError as ioe:
            dialog_error(f"File Error: {ioe}")
        except Exception as e:  # pylint: disable=broad-exception-caught
            dialog_error(f"An unexpected error occurred: {e}")
            traceback.print_exc()
     
     
    def dialog_success(message: str) -> None:
        """Display a success message dialog."""
        dialog = Gtk.MessageDialog(
            transient_for=window,
            modal=True,
            message_type=Gtk.MessageType.INFO,
            buttons=Gtk.ButtonsType.OK,
            text="Success",
            secondary_text=message,
        )
        dialog.run()  # type: ignore
        dialog.destroy()
     
     
    def dialog_error(message: str) -> None:
        """Display an error message dialog."""
        dialog = Gtk.MessageDialog(
            transient_for=window,
            modal=True,
            message_type=Gtk.MessageType.ERROR,
            buttons=Gtk.ButtonsType.OK,
            text="Error",
            secondary_text=str(message),
        )
        dialog.run()  # type: ignore
        dialog.destroy()
     
    # -------------------- Main GTK Window Setup -------------------- #
     
    window = Gtk.Window(title="Hexagonal Grid Generator")
    window.set_border_width(10)
    window.set_default_size(400, 350)
    window.connect("destroy", Gtk.main_quit)
     
    vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
    window.add(vbox)
     
    grid_layout = Gtk.Grid(column_spacing=10, row_spacing=5)
    vbox.pack_start(grid_layout, True, True, 0)
     
    row_index: int = 0
     
    # --- Widgets ---
     
    label_grid_width = Gtk.Label(label="Grid Width:", xalign=0)
    entry_grid_width = Gtk.Entry()
    entry_grid_width.set_text(str(grid_width))
    grid_layout.attach(label_grid_width, 0, row_index, 1, 1)
    grid_layout.attach(entry_grid_width, 1, row_index, 1, 1)
    row_index += 1
     
    label_grid_height = Gtk.Label(label="Grid Height:", xalign=0)
    entry_grid_height = Gtk.Entry()
    entry_grid_height.set_text(str(grid_height))
    grid_layout.attach(label_grid_height, 0, row_index, 1, 1)
    grid_layout.attach(entry_grid_height, 1, row_index, 1, 1)
    row_index += 1
     
    label_side_length = Gtk.Label(label="Side Length:", xalign=0)
    entry_side_length = Gtk.Entry()
    entry_side_length.set_text(str(side_length))
    grid_layout.attach(label_side_length, 0, row_index, 1, 1)
    grid_layout.attach(entry_side_length, 1, row_index, 1, 1)
    row_index += 1
     
    label_output_filename = Gtk.Label(label="Output Filename:", xalign=0)
    entry_output_filename = Gtk.Entry()
    entry_output_filename.set_text(output_filename)
    grid_layout.attach(label_output_filename, 0, row_index, 1, 1)
    grid_layout.attach(entry_output_filename, 1, row_index, 1, 1)
    row_index += 1
     
    label_orientation = Gtk.Label(label="Orientation:", xalign=0)
    radio_pointy_top = Gtk.RadioButton.new_with_label_from_widget(None, "Pointy Top")
    radio_flat_top = Gtk.RadioButton.new_with_label_from_widget(
        radio_pointy_top, "Flat Top"
    )
    radio_flat_top.set_active(True)
     
    hbox_orientation = Gtk.Box(spacing=6)
    hbox_orientation.pack_start(radio_pointy_top, False, False, 0)
    hbox_orientation.pack_start(radio_flat_top, False, False, 0)
    grid_layout.attach(label_orientation, 0, row_index, 1, 1)
    grid_layout.attach(hbox_orientation, 1, row_index, 1, 1)
    row_index += 1
     
    button_box = Gtk.Box(spacing=10)
    vbox.pack_start(button_box, False, False, 0)
     
    generate_button = Gtk.Button(label="Generate")
    generate_button.connect("clicked", on_generate_clicked)
    button_box.pack_start(generate_button, True, True, 0)
     
    close_button = Gtk.Button(label="Close")
    close_button.connect("clicked", lambda _: Gtk.main_quit())  # type: ignore
    button_box.pack_start(close_button, True, True, 0)
     
    window.show_all()
    Gtk.main()


    Je comprend bien que votre code ne sera pas lu par vos élèves, mais il le sera par vous dans plusieurs mois, vous devriez prévoir ce cas...
    Images attachées Images attachées  

Discussions similaires

  1. Réponses: 145
    Dernier message: 15/02/2009, 12h51
  2. Faire communiquer deux programmes python
    Par bestdomdom dans le forum Général Python
    Réponses: 5
    Dernier message: 26/10/2006, 10h30
  3. [Lien]erreur dans mon programme python
    Par durnambule dans le forum Général Python
    Réponses: 11
    Dernier message: 29/01/2004, 15h59

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo