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

Python Discussion :

Async - await / if / while [Python 3.X]


Sujet :

Python

  1. #1
    Membre du Club
    Homme Profil pro
    Neuropsy
    Inscrit en
    Juin 2022
    Messages
    7
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : France, Landes (Aquitaine)

    Informations professionnelles :
    Activité : Neuropsy
    Secteur : Santé

    Informations forums :
    Inscription : Juin 2022
    Messages : 7
    Par défaut Async - await / if / while
    Bonjour à toutes et tous !

    Voici quelques heures que j'essaye de faire tourner le programme Github suivant sur ma bécane : https://github.com/riktw/AN9002_info
    Il s'agit de récupérer les données d'un multimètre, envoyées par bluetooth, sur mon PC (HP ; Édition Windows 10 Famille).

    Après plusieurs péripéties car je suis débutant, j'ai pu installer pip, python, git, matplotlib et d'autres modules. J'ai réussi à choper les coordonnées bluetooth de mon multimètre et ses coordonnées UUID. J'ai commencé ce jour à reprendre le code sur VS Code 2022. Je me suis rendu compte que c'était un code pour Mac puisque le module resource utilisé est un module Mac (je l'ai remplacé par psutil). Pour le module platform, VS Code dit : "platform is not accessed". Idem pour le module logging

    Mais quand même ça s'est compliqué. Je suppose que le fichier multimeter.py est le fichier de démarrage. Je le lance, rien ne se passe. Par contre, le fichier logdata.py lui est bourré d'erreur selon vscode.

    LogData.py avec mes modifications :
    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
    import sys
    import asyncio
    import platform 
    import logging 
    import keyboard
    import csv
     
    from multimeter import *
    import matplotlib.pyplot as plt
    from bleak import BleakClient
     
    ADDRESS = ("FC:58:FA:53:61:C0")
     
    CHARACTERISTIC_UUID = '0000fff0-0000-1000-8000-00805f9b34fb'  # <--- Change to the characteristic you want to enable notifications from.
     
    dataGraph = []
    multimeter = ['AN9002']
    lastDisplayedUnit = ""
     
    def notification_handler(sender, data):
        global dataGraph
        global multimeter
        global lastDisplayedUnit
        """Simple notification handler which prints the data received."""
        #print("Data multimeter: {0}".format(data.hex(' ') ))
        multimeter.SetMeasuredValue(data)
        displayedData = multimeter.GetDisplayedValue()
        if multimeter.overloadFlag:
            displayedData = 99999
            print("Overload")
     
        unit = multimeter.GetDisplayedUnit()
        if lastDisplayedUnit == "":
            lastDisplayedUnit = unit
     
        if unit != lastDisplayedUnit:
            lastDisplayedUnit = unit
            dataGraph.clear()
            plt.clf()
     
        dataGraph.append(displayedData)
        plt.ylabel(unit)
        print(str(displayedData) + " " + unit) 
     
     
    async def run(address): client: BleakClient(address)
        try: 
            await client.connect()
            await client.start_notify(CHARACTERISTIC_UUID, notification_handler)
            while(1):
                if keyboard.is_pressed("q"):
                    print("Shutting down!");
                    break;
                else:
                    plt.plot(dataGraph, color='b')
                    plt.draw()
                    plt.pause(0.1)
                    await asyncio.sleep(0.5)       
     
        except Exception as e:
            print(e)
        finally:
            await client.stop_notify(CHARACTERISTIC_UUID)
            await client.disconnect()
     
     
    if __name__ == "__main__":
        loop = asyncio.get_event_loop()
        loop.set_debug(False)
        loop.run_until_complete(run(ADDRESS))
     
        with open('plot.csv', 'w') as f:
            wr = csv.writer(f)
            wr.writerow(dataGraph)

    Réponses de l'environnement Python :
    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
    fenêtre interactive Python 3.10 (64-bit) [PTVS 17.0.22089.1-17.0]
    Tapez $help pour obtenir la liste des commandes.
    >>> import sys
    >>> import asyncio
    >>> import platform
    >>> import logging
    >>> import keyboard
    >>> import csv
    >>> from multimeter import *
    >>> import matplotlib.pyplot as plt
    >>> from bleak import BleakClient
    >>> ADDRESS = ("FC:58:FA:53:61:C0")
    >>> CHARACTERISTIC_UUID = '0000fff0-0000-1000-8000-00805f9b34fb'  # <--- Change to the characteristic you want to enable notifications from.
    >>> dataGraph = []
    >>> multimeter = ['AN9002']
    >>> lastDisplayedUnit = ""
    >>> def notification_handler(sender, data):
    ...     global dataGraph
    ...     global multimeter
    ...     global lastDisplayedUnit
    ...     """Simple notification handler which prints the data received."""
    ...     #print("Data multimeter: {0}".format(data.hex(' ') ))
    ...     multimeter.SetMeasuredValue(data)
    ...     displayedData = multimeter.GetDisplayedValue()
    ...     if multimeter.overloadFlag:
    ...         displayedData = 99999
    ...         print("Overload")
    ...     
    ...     unit = multimeter.GetDisplayedUnit()
    ...     if lastDisplayedUnit == "":
    ...         lastDisplayedUnit = unit
    ...     
    ...     if unit != lastDisplayedUnit:
    ...         lastDisplayedUnit = unit
    ...         dataGraph.clear()
    ...         plt.clf()
    ...     
    ...     dataGraph.append(displayedData)
    ...     plt.ylabel(unit)
    ...     print(str(displayedData) + " " + unit) 
    ...      
    ... 
    >>> async def run(address): client: BleakClient(address)
    >>>     try:
      File "<stdin>", line 1
        try:
    IndentationError: unexpected indent
    >>>         await client.connect()
      File "<stdin>", line 1
        await client.connect()
    IndentationError: unexpected indent
    >>>         await client.start_notify(CHARACTERISTIC_UUID, notification_handler)
      File "<stdin>", line 1
        await client.start_notify(CHARACTERISTIC_UUID, notification_handler)
    IndentationError: unexpected indent
    >>>         while(1):
      File "<stdin>", line 1
        while(1):
    IndentationError: unexpected indent
    >>>             if keyboard.is_pressed("q"):
      File "<stdin>", line 1
        if keyboard.is_pressed("q"):
    IndentationError: unexpected indent
    >>>                 print("Shutting down!");
      File "<stdin>", line 1
        print("Shutting down!");
    IndentationError: unexpected indent
    >>>                 break;
      File "<stdin>", line 1
        break;
    IndentationError: unexpected indent
    >>>             else:
      File "<stdin>", line 1
        else:
    IndentationError: unexpected indent
    >>>                 plt.plot(dataGraph, color='b')
      File "<stdin>", line 1
        plt.plot(dataGraph, color='b')
    IndentationError: unexpected indent
    >>>                 plt.draw()
      File "<stdin>", line 1
        plt.draw()
    IndentationError: unexpected indent
    >>>                 plt.pause(0.1)
      File "<stdin>", line 1
        plt.pause(0.1)
    IndentationError: unexpected indent
    >>>                 await asyncio.sleep(0.5)
      File "<stdin>", line 1
        await asyncio.sleep(0.5)
    IndentationError: unexpected indent
    >>>     except Exception as e:
      File "<stdin>", line 1
        except Exception as e:
    IndentationError: unexpected indent
    >>>         print(e)
      File "<stdin>", line 1
        print(e)
    IndentationError: unexpected indent
    >>>     finally:
      File "<stdin>", line 1
        finally:
    IndentationError: unexpected indent
    >>>         await client.stop_notify(CHARACTERISTIC_UUID)
      File "<stdin>", line 1
        await client.stop_notify(CHARACTERISTIC_UUID)
    IndentationError: unexpected indent
    >>>         await client.disconnect()
      File "<stdin>", line 1
        await client.disconnect()
    IndentationError: unexpected indent
    >>> if __name__ == "__main__":
    ...     loop = asyncio.get_event_loop()
    ...     loop.set_debug(False)
    ...     loop.run_until_complete(run(ADDRESS))
    ...     
    ... 
    <stdin>:2: DeprecationWarning: There is no current event loop
    >>>     with open('plot.csv', 'w') as f:
      File "<stdin>", line 1
        with open('plot.csv', 'w') as f:
    IndentationError: unexpected indent
    >>>         wr = csv.writer(f)
      File "<stdin>", line 1
        wr = csv.writer(f)
    IndentationError: unexpected indent
    >>>         wr.writerow(dataGraph)

    Je suppose que que asyncio/await et consorts sont à la ramasse mais je n'ai pas trouvé de réponse à cette situation.

    Si vous pouviez m'aider à résoudre ce mystère ça serait super sympa !
    Merci d'avance et bonne journée !
    Moustache

  2. #2
    Membre Expert
    Homme Profil pro
    Développeur informatique
    Inscrit en
    Février 2003
    Messages
    1 603
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur informatique
    Secteur : Industrie

    Informations forums :
    Inscription : Février 2003
    Messages : 1 603
    Par défaut
    Beaucoup de lignes mentionnent un soucis d'indentation dans le code.

    Regardez de ce côté là pour commencer.

  3. #3
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 715
    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 715
    Par défaut
    Salut,

    Un script python est un fichier texte à lancer avec l'interpréteur Python via une commande comme python script.py.
    Là ce que vous avez fait c'est un copier/coller du contenu d'un fichier (script) dans l'interpréteur interactif.

    Vous devez maîtriser un peu l'environnement dans lequel vous travaillez... et ça n'a rien à voir avec la programmation Python (ou les async/await).

    De plus récupérer du code sur Internet est une bonne chose à partir du moment où vous n'avez pas à le modifier pour en profiter. Sinon vous devez comprendre ce que vous y changez et avoir un niveau proche de ceux qui ont programmé ce script là.

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

  4. #4
    Membre du Club
    Homme Profil pro
    Neuropsy
    Inscrit en
    Juin 2022
    Messages
    7
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 37
    Localisation : France, Landes (Aquitaine)

    Informations professionnelles :
    Activité : Neuropsy
    Secteur : Santé

    Informations forums :
    Inscription : Juin 2022
    Messages : 7
    Par défaut
    Bonjour et merci pour vos réponses.

    Je me suis mis en contact avec le concepteur du code pour lui demander de l'aide mais c'est resté sans réponse. L'auteur du code invite les gens à le tester et lui faire des retours.
    J'ai testé ça n'a pas marché et je veux juste comprendre pourquoi.

    Merci tout de même

  5. #5
    Expert éminent
    Homme Profil pro
    Architecte technique retraité
    Inscrit en
    Juin 2008
    Messages
    21 715
    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 715
    Par défaut
    Citation Envoyé par MoucheTaMoustache Voir le message
    J'ai testé ça n'a pas marché et je veux juste comprendre pourquoi.
    Lorsque l'interpréteur interactif voit qu'une ligne se termine par ':', il ouvre un block et le signale en changeant le prompt de '>>>' à '...'.
    Exemple:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    >>> if True:
    ...    print ('foo')
    ...    print ('bar')
    ...
    foo
    bar
    et le block se termine lorsqu'on entre une ligne vide.
    Mais s'il n'y a qu'une instruction, je peux l'ajouter sur la même ligne après le ':'. L'interpréteur Python considère alors qu'il n'y a que cette instruction dans le block.
    Si j'écris:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    >>> if True: print('foo')
    ...    print('bar')
      File "<stdin>", line 2
        print('bar')
    IndentationError: unexpected indent
    >>>
    il attend une fin de ligne, pas une nouvelle instruction.

    Vous vous êtes planté en recopiant: >>> async def run(address): client: BleakClient(address)Pour le reste, je vous le répète: pas de copier/coller d'un script complexe dans l'interpréteur interactif, lancez le script "normalement" (et s'il plante c'est que vous avez probablement un soucis de copier/coller).

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

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 8
    Dernier message: 28/08/2014, 08h23
  2. Réponses: 11
    Dernier message: 21/05/2014, 09h41
  3. [C#] Différence Async, Await, MultiThreading
    Par same66 dans le forum Débuter
    Réponses: 2
    Dernier message: 14/03/2013, 09h25
  4. Réponses: 2
    Dernier message: 13/03/2013, 19h16
  5. Async/Await avec Silverlight & WCF
    Par Joffrey Kern dans le forum Silverlight
    Réponses: 5
    Dernier message: 24/05/2012, 09h45

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