FEATHER-CHARGER-MODULE-IMPORT

De MCHobby - Wiki
Sauter à la navigation Sauter à la recherche


MCHobby investit du temps et de l'argent dans la réalisation de traduction et/ou documentation. C'est un travail long et fastidieux réalisé dans l'esprit Open-Source... donc gratuit et librement accessible.
SI vous aimez nos traductions et documentations ALORS aidez nous à en produire plus en achetant vos produits chez MCHobby.
Page-under-construction.pngPage(s) en cours de traduction/élaboration.

Page(s) under translation/construction

Importer un fichier de code

Comme pour une version standard de Python, vous pouvez importer et exécuter du code provenant de fichiers python dans votre script MicroPython. Cette approche est idéal pour décomposer un long script ou script complexe en des morceaux de codes plus petits. Cela permet de réutiliser ou partager du code entre plusieurs project. Cela facilite également le processus de maintenance.

Si vous n'avez pas l'habitude des modules Python alors vous devriez prendre connaissance de la documentation officielle (Python.org, Anglais). Python vous permet de placer du codans dans un fichier .py puis de l'importer depuis un autre script se trouvant dans le même répertoire. Vous pouvez même opter pour une approche plus avancée en créant un paquet (package en anglais) contenant plusieurs fichiers .py que vous pourrez exposer de différentes façons. La plupart des bibliothèques Python tierces sont disponibles sous forme de paquet que vous pouvez installer et importer dans vos propres scripts.

Nous allons commencer par voir comment importer du code depuis un simple fichier .py dans votre script MicroPython. Assurez-vous d'avoir une carte fonctionnant sous MicroPython et de vous être familiarisé avec les manipulations de fichier sur votre carte.

Ensuite, nous allons commencer par créer un petit fichier Python sur notre ordinateur, il contiendra quelques fonctions. Créez le fichier test.py avec un éditeur de texte et copiez y le code suivant:

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

La fonction add() permet de faire l'addition de deux valeurs tandis que la fonction substract() effectue une soustraction.

Page-under-construction.pngPage(s) en cours de traduction/élaboration.

Page(s) under translation/construction

Try using the code on your computer first with the desktop version of Python before trying it in MicroPython. In a terminal navigate to the same directory as the test.py file (this is very important, you must be in the same directory as test.py!) and run the python3 command (or python if using Python 2.x). At the Python REPL enter the following commands:

import test
test.add(1, 1)

You should see the add function called and the result of 1 + 1 returned. If you see an ImportError that the test module can't be found make sure you're running Python from the same directory as test.py is located.

Try calling the subtract function just like the add function was called. Remember you need to add the module name in front of the function when you call it!

{{{2}}}
Crédit: AdaFruit Industries www.adafruit.com

Now that you see how a simple .py file import works on your computer try doing the same with MicroPython. Copy the test.py file to the root of your board's filesystem. For example if you're using a tool like ampy to copy files you would run something like:

ampy --port /board/serial/port put test.py

Then connect to the board's REPL and run the same Python code to import and use the module:


import test
test.add(1, 1)
test.subtract(1, 1)

{{{2}}}
Crédit: AdaFruit Industries www.adafruit.com

You should see the functions run just like they did on your computer! If you see an ImportError double check you copied the test.py file to the root of the board's filesystem and try again.

Importing and using code from a .py file in MicroPython is as easy as copying the file to the board and importing to use as above. Remember the file needs to be in the same location as the script which is importing and using it. In most cases your scripts will be in the root of the board's filesystem so that's usually where you want to place .py files which will be imported.

You can import and call more than just functions in your scripts too. Anything inside test.py like classes, functions, global variables, etc. will be availabe to your script after the import command runs. In fact you can see exactly what is in the module with the dir command, for example in the REPL run:

import test
dir(test)

{{{2}}}
Crédit: AdaFruit Industries www.adafruit.com

You should see a list of everything that was imported from the module, including the add and subtract functions (the __name__ variable is something Python adds to let the module know what its name is).

Les paquets (Packages)

Sometimes your code can get so complex that putting it into a single file doesn't make sense. In these cases you can break code into multiple files and create a Python package that puts all the code together into what looks like a simple module your scripts can import. MicroPython supports the concept of Python packages just like normal Python so you can better structure complex scripts.

First be sure to read the official documentation on Python packages. Packages in MicroPython for the most part work just the same as in Python.

Now create a Python package on your computer by creating a directory called test. Inside that directory create a file called add.py and place inside it the add function code:

def add(a, b):
    return a + b

Create a file subtract.py in the same location and place in it the subtract function code:

def subtract(a, b):
    return a - b

Finally create a file called __init__.py in the same location and enter the following code to import and expose the functions from the files above:

from test.add import add
from test.subtract import subtract

Be sure to call this file exactly __init__.py! Python looks for this file name to know that it found a package. If you don't have this file or if it's not named correctly then Python will fail to import the package!

The code inside __init__.py runs when the package is imported in a script. You can see this code imports the add function from the add.py script in the package, and the subtract function from the subtract.py script.

Notice the import statements refer to add.py by its full 'absolute import' name of test.add. The test. in front of add is the package name, i.e. the name of the package directory. You can't run a command like "from add import add" in the __init__.py since Python would get confused if it should load an add.py from inside the module or from elsewhere. Using the full name test.add tells Python to use the add.py module inside the test package directory.

Double check you have a test package structure that looks like the following:

  • test directory
    • __init__.py file which imports the add and subtract functions
    • add.py which exposes the add function
    • subtract.py which exposes the subtract function

Now try importing and using the package with desktop Python. In a terminal navigate to the parent of the test package directory (i.e. one folder above it). Importing and using a package is just like importing a .py file however Python treats the entire test directory as the package itself. This means you need to run Python from above the test directory so Python can find the package.

Also note be sure you don't have a test.py file in the same directory as the test package! If you do Python could get confused and import the test.py file instead of the test package. Delete test.py if it exists next to the test package folder!

Run the following code in the Python REPL to import and use the add and subtract functions from the test package:

import test
test.add(1, 1)
test.subtract(1, 1)

{{{2}}}
Crédit: AdaFruit Industries www.adafruit.com

You should see the package imported and the functions work exactly as you saw before! If you see an ImportError that the test module doesn't exist be sure you're running Python from the parent of the test package directory!

Now try copying the package to your MicroPython board and using it exactly as you did with desktop Python. Again make sure a test.py file doesn't exist on the board or else MicroPython will be confused about what to import! If you have test.py on your board already you can delete it using the following ampy command:

ampy --port /board/serial/port rm test.py

Now create the test package directory in the root of the board:

ampy --port /board/serial/port mkdir test

And copy inside the three .py files above that define the package (run these commands from inside the test package folder):

ampy --port /board/serial/port put __init__.py test/__init__.py
ampy --port /board/serial/port put add.py test/add.py
ampy --port /board/serial/port put subtract.py test/subtract.py

These commands will copy the .py files to the test folder on the board's filesystem. Use the ls command to double check there's a test folder with these three files on your board:

ampy --port /board/serial/port ls test

{{{2}}}
Crédit: AdaFruit Industries www.adafruit.com

Connect to the board's REPL and try importing the test package and using its functions as before:

import test
test.add(1, 1)
test.subtract(1, 1)

{{{2}}}
Crédit: AdaFruit Industries www.adafruit.com

You should see the package import and the functions work exactly as before when they were in a single test.py file!

Breaking a complex module apart into multiple files with a package is a great way to simplify and structure code. In this simple example it seems like a bit of unnecessary work, but as scripts get more complex and re-use common code it will help immensely to break them into modules and packages. You can even start to share code with others by giving them your modules and packages to load and use!


Source: MicroPython Basics: Loading Modules
Créé par Tony DiCola pour AdaFruit Industries.

Traduit par Meurisse D. pour MCHobby

Toute référence, mention ou extrait de cette traduction doit être explicitement accompagné du texte suivant : «  Traduction par MCHobby (www.MCHobby.be) - Vente de kit et composants » avec un lien vers la source (donc cette page) et ce quelque soit le média utilisé.

L'utilisation commercial de la traduction (texte) et/ou réalisation, même partielle, pourrait être soumis à redevance. Dans tous les cas de figures, vous devez également obtenir l'accord du(des) détenteur initial des droits. Celui de MC Hobby s'arrêtant au travail de traduction proprement dit.

Traduit avec l'autorisation d'AdaFruit Industries - Translated with the permission from Adafruit Industries - www.adafruit.com