Python

Learn Python : https://www.stavros.io/tutorials/python/

Exemples de code : https://github.com/EditionsENI/python-raspberrypi

Exécution : python3 main.py ou bien précisez en 1ere ligne #!/usr/bin/env python3 et rendez le fichier exécutable puis lancez le par ./test.py

#!/usr/bin/env python3

hello=’Hi’

print(‘hello’)

Test de code : python3 -c « print(‘Hello’); print(‘world’) »

IDE utilisée : PY Charm

I) Conventions :

Il n’y a pas de délimitation de blocs avec par exemple de ‘{ »}’ mais une indentation de 4 espaces ou de la touche tab.

Des fonctions natives existent telle que round, abs… https://docs.python.org/fr/3.7/library/functions.html?highlight=round

a. Fonctions :

>>> def augmente_moi(a):
...     return augmente_moi + 2
... 
>>> augmente_moi(1)
3

Remarque, print est une fonction (à partir de Python 3) :

print("There are <", 2**32, "> possibilities!")

b. IF

>>> a = 5
>>> if a > 5:
...     a = a + 1
... elif a == 5:
...     a = a + 1000
... else:
...     a = a - 1
... 
>>> a
1005

c. Boucle

i = 0
while i < 10:
print(« Je ne dois pas poser « ,i, » question sans lever la main »)
i = i +1

z. Documentation :

Python has one more feature that simplifies docstring creation. Instead of directly manipulating the __doc__ property, the strategic placement of the string literal directly below the object will automatically set the __doc__ value. Here’s what happens with the same example as above:

def say_hello(name):
    """A simple function that says hello... Richie style"""
    print(f"Hello {name}, is it me you're looking for?")

>>>

>>> help(say_hello)
Help on function say_hello in module __main__:

say_hello(name)
    A simple function that says hello... Richie style

Tuto pour documenter

Pour créer de la documentation, soit ajoutez des remarques avec un # ou bien utilisez « docstring ».

def say_hello(name):
    """A simple function that says hello...La documentation peut servir à faire des tests. A l'aide de DocTest Richie style"""
    print(f"Hello {name}, is it me you're looking for?")

La documentation peut servir à faire des tests. A l’aide de DocTest

Références :

https://python.doctor/

A) Installation :

https://www.python.org/downloads/release/python-373/

Install PIP : sudo apt install python3-pip (lancement PIP3)
 
PyQt est un module libre qui permet de créer des interfaces graphiques en Python.
pip3 install --user pyqt5  
sudo apt-get install python3-pyqt5  
sudo apt-get install pyqt5-dev-tools
sudo apt-get install qttools5-dev-tools
Pour l’exécution : qtchooser -run-tool=designer -qt=5
 
GTK :

 

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
xxxxxxx
label = Gtk.Label(label="This is a normal label")
 
 

B) Pour Android KIVY :

Python sous android : https://python-for-android.readthedocs.io/en/latest/

Installation sous windows :

https://kivy.org/doc/stable/installation/installation-windows.html#install-win-dist

Installation sous Linux :

https://kivy.org/doc/stable/installation/installation-linux.html

https://realpython.com/mobile-app-kivy-python/#understanding-the-kivy-framework

1°) Créer un environnement virtuel :

python3 -m venv my_kivy_project

source my_kivy_project/bin/activate

2°) installer Kivy :

python -m pip install kivy

Exemple :

http://tableauxmaths.fr/spip/spip.php?rubrique74

https://ressources.labomedia.org/Kivy_Exemples_simples_pour_apprendre

Utilisation de Buildozer :

Installation :

wget https://github.com/HeaTTheatR/KivyMD-data/raw/master/install-kivy-buildozer-dependencies.sh


chmod +x install-kivy-buildozer-dependencies.sh

./install-kivy-buildozer-dependencies.sh

Exécution

1°) Renommer le fichier source xxx.py en main.py

2°) tapez buildozer init

3°) éditer le fichier spec (le répertoire du fichier main.py est soit ‘.’ pour le répertoire actuel ou autre si il est ailleurs…) ajouter dans le paragraphe requirements : pillow

4°) lancer la conversion : buildozer android debug

Avec si besoin : python -m pip install cython

Références :

https://resesources.labomedia.org/kivy_buildozer_pour_creer_une_application_android_avec_un_script_python

https://avionmission.github.io/blog/convert-py-to-apk-using-python-and-buildozer/

D) IDE :

THONNY

Utilisez IDLE (sous Windows via le menu démarrer) sous Linux sudo apt-get install idle-python3.xxx

PYCHARM : Ide Windows et Linux

Eric6 sous Linux : QT Setting : /usr/lib/qt5/bin
 
 
Install Documentation : install either of the rope or jedi
plugins - in the plugins list, rope is called "Refactoring, Rope" and 
jedi is called "Completions, Jedi".

Eric Python IDE : https://eric-ide.python-projects.org/eric-tutorials.html
 
 

E) Tuto / apprentissage :

x = 1
if x == 1:
    # retrait de quatre espaces
    print("x vaut 1.")
xxx

https://www.commonlounge.com/discussion/9921697e30ef4d74999c7f0087bb7edd?r=qp$-py-hid-adc_hqt_dct_dpt

C) Framework Python destiné au web : Django 

1°) Créer ou upgrader un utilisateur avec la possibilité d’avoir des droits root (sudo) : sudo usermod -aG sudo <<user>>

puis se loguer avec cet utilisateur : su – <<user>>

https://www.digitalocean.com/community/tutorials/how-to-create-a-new-sudo-enabled-user-on-ubuntu

2°) installer les environnements virtuels python, postegre et le serveur NGINX:

sudo apt update
sudo apt install python3-venv python3-dev libpq-dev postgresql postgresql-contrib nginx curl

3°) Créer une base de données PostGre avec utilisateur

sudo -u postgres psql

CREATE DATABASE myproject;

CREATE USER myprojectuser WITH PASSWORD ‘password’;

ALTER ROLE myprojectuser SET client_encoding TO ‘utf8’;
ALTER ROLE myprojectuser SET default_transaction_isolation TO ‘read committed’;
ALTER ROLE myprojectuser SET timezone TO ‘UTC’;

GRANT ALL PRIVILEGES ON DATABASE myproject TO myprojectuser;

\q

4°) Création d’un environnement virtuel pour le projet :

mkdir ~/myprojectdir
cd ~/myprojectdir

python3 -m venv myprojectenv

source myprojectenv/bin/activate

5°) Installation de Gunicorn (serveur HTTP WSGI Python pour UNIX) Django et psycopg2 (nécessaire pour se connecter à PostGre) :

pip install django gunicorn psycopg2-binary

6°) Création du site :

django-admin startproject project_name

cd project_name

django-admin startapp app_name

Lancement du site : python manage.py runserver (http://127.0.0.1:8000/)

https://medium.com/@kaushiksimran827/building-your-first-website-with-django-a-step-by-step-guide-for-beginners-a33710649d4b

https://openclassrooms.com/courses/developpez-votre-site-web-avec-le-framework-django/creez-vos-applications-web-avec-django

Utilisation json :

 pip install simplejson

import simplejson as json
j = json.loads(‘{« one » : « 1 », « two » : « 2 », « three » : « 3 »}’)
print (j[‘two’])

 pip install requests

import requests
r = requests.get(url=’https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty&rsquo;)
print(r.json())

Pour Requestshttp://fr.python-requests.org/en/latest/user/quickstart.html#creer-une-requete

https://stackoverflow.com/questions/35120250/python-3-get-and-parse-json-api

Pour connaitre la version installée :

python --version

Pour lire une page web : BeautifulSoup

# import libraries
import urllib.request
from bs4 import BeautifulSoup
# specify the url
quote_page = « http://www.bloomberg.com/quote/SPX:IND &raquo;
# query the website and return the html to the variable ‘page’
request = urllib.request.Request(quote_page)
response = urllib.request.urlopen(request)
# parse the html using beautiful soup and store in variable `soup`
soup = BeautifulSoup(response, « html.parser »)
# Take out the <div> of name and get its value
name_box = soup.find(« h1 », attrs={« class »: « name »})
name = name_box.text.strip() # strip() is used to remove starting and trailing
print (name)
# get the index price
price_box = soup.find(« div », attrs={« class »: »price »})
price = price_box.text.strip()
print (price)

http://apprendre-python.com/page-beautifulsoup-html-parser-python-library-xml

https://www.crummy.com/software/BeautifulSoup/bs4/doc/

Pour rendre un ficher python 2.x exécutable sous windows utilisez PyInstaller :

  • easy_install -U pip ==> Met à jour l’installateur pip.
  • pip install pyinstaller ==> Installe PyInstaller.

Utilisation :

  • pyinstaller VotreFichier.py : Création d’un exe et de tous les fichiers nécessaires dans le répertoire « dist »
  • pyinstaller -w -F VotreFichier.py : Création d’un exe d’un ficher python « windows » (utilisant Tkinter) en incorporant tous les fichiers nécessaires.

Pour changer l’icône, utilisez RessourceHacker 

Pour la version 3.x :

https://anthony-tuininga.github.io/cx_Freeze/

Références :

https://www.supinfo.com/articles/single/5437-distribuer-programme-python-avec-pyinstaller

Références :

http://www.tkdocs.com/tutorial/firstexample.html

http://apprendre-python.com/page-editeurs-python-gratuits-payants-ide

https://docs.python.org/3.6/tutorial/index.html

https://openclassrooms.com/courses/apprenez-a-programmer-en-python/des-interfaces-graphiques-avec-tkinter

https://anthony-tuininga.github.io/cx_Freeze/

Articles récents
Commentaires récents
fatima dans Bienvenue !
AdminDroid dans Bienvenue !
fatima dans Bienvenue !
Archives
Catégories