Liens
Astuces
|
import os
scriptFolderPath = os.path.realpath("")
""" Docstring
Multi-lignes """
exit("texte")
variable1 = None
import time
time.sleep(1)
execfile(r'chemin vers le fichier de script')
import os
if os.getuid() == 0:
else:
print("Lancer le script avec sudo.")
|
Package et modules (fichiers *.py) |
lower_case_with_underscores
|
Classes |
CapWords (PascalCase, UpperCamelCase)
|
Fonctions |
lower_case_with_underscores
|
Méthodes “privées” |
_start_with_underscores
|
Console I/O
|
nombre = input('Entrez un nombre > ')
print(nombre)
os.system('cls')
print('Texte ', variable1, ' suite')
print('Texte ' + str(variable1) + ' suite')
print('Texte {} suite'.format(variable1))
print("Texte", end="")
import sys
sys.stdout.write("Texte")
|
 |
optparse est obsolète, utiliser argparse |
|
from argparse import ArgumentParser
parser = ArgumentParser(prog='myprogram', description='Courte description du programme')
parser.add_argument('action')
parser.add_argument('-f', '--file')
parser.add_argument("-r", "--recursive", action="store_true", help="description de l'argument. [default: %(default)s]"))
parser.add_argument('-v', '--version', action='version', version='%(prog)s v1.0 (2017-07-03)')
args = parser.parse_args()
file = args.file
recursive = args.recursive
|
usage: myprogram [-h] [-f FILE] [-r] [-v] action
Courte description du programme
positional arguments:
action
optional arguments:
-h, --help show this help message and exit
-f FILE, --file FILE
-r, --recursive description de l'argument. [default: False]
-v, --version show program's version number and exit
sys.argv
|
import sys
if len(sys.argv) != 2:
exit('Utilisation: {} argument1'.format(os.path.basename(sys.argv[0])))
sys.argv[0]
sys.argv[1]
|
 |
Python 3 utilise la table unicode pour les string. |
|
longueur = len(string1)
print(r'test \n test')
string2.find('deux')
string2 = string1.replace(".", "!")
|
Fichier:Py.svg
|
string1 = 'un'
string2 = string1 + ' - deux'
string2 += ';'
string2 = f'{string1} - deux'
|
Fichier:Py.svg
|
string3 = ''
if not string3:
if string1.lower() == string2.lower():
if string1.endswith('xxx'):
|
Split
Fichier:Py.svg
|
url = 'http://www.domain.fr/fichier.txt'
url.split('/')
url.split('/')[-1]
url.split('/', 1)
url.rsplit('/', 1)
url.rsplit('/', 1)[1]
|
Nombres
|
entier = 1
décimal = 2.0
somme = entier + décimal
int(décimal)
float(entier)
|
Booléen
|
vrai = True
faux = False
int(vrai)
int(faux)
|
|
import datetime
from dateutil.parser import parse
ma_variable = f'text-{datetime.date.today()}-text}'
ma_variable = "text-%s-text" % ( datetime.date.today() )
parse('03/08/2017')
parse('03/08/2017', dayfirst=True)
|
Python: Get Today’s Current Date and Time
If else
|
if a == b and a == c or b != c:
commande1
commande2
elif not b == c:
commande3
else:
commande4
if myInteger:
print('myInteger is defined and not equal to 0')
if myString:
print('myString is defined and not an empty string')
commande1 if a == b else commande2
|
|
myList = []
myList = ['zéro', 1, 'deux', 'trois']
myList[1]
myList[1] = 'un'
myList[:2]
myList[2:]
myList[1:3]
myList[-1]
myList[-2:]
myList[-3:-1]
myList[0:4:2]
myList.append(4)
del myList[1]
myList.pop(1)
myList.remove('deux')
len(myList)
if 4 in myList:
myList.sort()
myList.sort(reverse=True)
import locale
locale.setlocale(locale.LC_ALL, '')
myList.sort(key=locale.strxfrm)
''.join(myList)
range(6)
range(5, 11)
range(0, 11, 2)
|
|
[x for x in range(6) if x%2 == 0]
filter(lambda x: x%2 == 0, range(6))
[x*2 for x in range(6)]
map(lambda x: x*2, range(6))
|
yield
Avec yield, le code n'est pas exécuté à l'appel de la méthode mais à la demande.
|
def my_method(max_value):
for i in range(max_value)
yield i*2
my_generator = my_method(10)
for i in my_generator:
|
|
for a,b,c in zip(myList[::3], myList[1::3], myList[2::3]):
print('{:<30}{:<30}{:<}'.format(a,b,c))
|
Tuple
|
myTuple = ('un', 'deux', 'trois')
|
|
dico = {}
dico = {'key a': 'value a', 'key b': 'value b'}
dico['key a']
dico['key c']
dico.get('key c')
dico.get('key c', 'Unknown')
dico['key c'] = 'value c'
del dico['key b']
for k, v in dico.items():
print(k, v)
|
Collection d'éléments unique indexés. Utilisé pour les opérations telles que intersection ou difference
Fichier:Py.svg
|
my_set = set(my_list)
diff = my_set.difference(my_other_set)
|
For
|
animaux = ['chat', 'serpent']
for animal in animaux:
print(animal)
break
continue
else:
print("fin sans break")
list = ['aa', 'ab', 'ac']
[print(x[1]) for x in list if x.endswith('b')]
for y in (x[1] for x in list if x.endswith('b')):
print(y)
z = lambda x: print(x[1]) if x.endswith('b') else None
[z(x) for x in list]
for folder in filter(lambda folder: os.path.isdir(os.path.join(cwd, folder)), os.listdir()):
|
While
|
i = 0
while i < 10:
i += 1
list = [1, 2, 3]
while 3 in list:
|
|
try:
raise Exception('EEE')
except ImportError:
pass
except (RuntimeError, TypeError, NameError):
pass
except Exception as e:
print(e)
except:
raise
else:
pass
|
Méthodes
|
Description
|
match() |
Determine if the RE matches at the beginning of the string.
|
search() |
Scan through a string, looking for any location where this RE matches.
|
findall() |
Find all substrings where the RE matches, and returns them as a list.
|
finditer() |
Find all substrings where the RE matches, and returns them as an iterator.
|
split() |
Split the string into a list, splitting it wherever the RE matches
|
sub() |
Find all substrings where the RE matches, and replace them with a different string
|
subn() |
Does the same thing as sub(), but returns the new string and the number of replacements
|
Compilation Flags
|
|
DOTALL, S |
Make . match any character, including newlines
|
IGNORECASE, I |
Do case-insensitive matches
|
MULTILINE, M |
Multi-line matching, affecting ^ and $ ^ devient le début de ligne au lieu du début du texte $ devient la fin de ligne au lieu de la fin du texte
|
search
|
import re
regex = re.compile('expression rationnelle')
match = re.search(regex, 'texte')
if match:
print('Une correspondance a été trouvée: ', match.group(0))
else:
print "l'expression %r n'a pas été trouvée" % (regex)
match = re.search(r"(\w+) (\w+)", "John Smith")
print match.group(0)
print match.group(1)
print match.group(2)
|
finditer
|
for match in re.finditer('(?P<groupe1>\d+) (?P<groupe2>\d+)', texte):
match.groupdict()
|
Substitution
|
import re
nouveauTexte = re.sub('expression rationnelle', 'substitution', 'texte')
nouveauTexte = re.sub(re.compile('expression rationnelle', re.MULTILINE), 'substitution', 'texte')
nouveauTexte = re.sub('expression rationnelle', 'substitution', 'texte', flags=re.MULTILINE)
re.sub('(texte) (intéressant)', '\g<2> \g<1>', 'un texte intéressant')
|
Fonctions
|
def my_function(arg1, arg2):
'''
Description de la fonction.
:param arg1: Description de l'argument.
:param arg2: Description de l'argument.
:return: Description du contenu retourné par la fonction.
'''
return f'{arg1} - {arg2}'
def my_function(arg1: str, arg2: str) -> str:
return f'{arg1} - {arg2}'
my_function('start', 'end')
def my_function(arg1, arg2 = 'end'):
return f'{arg1} - {arg2}'
my_function('start')
my_function('start', 'next')
def my_function(*args):
return ' - '.join(args)
my_function('start', 'next', 'end')
def my_function(**kwargs):
for k, v in kwargs.items():
yield f'{k} - {v}'
'\n'.join(my_function(un = 1, deux = 2))
|
- Les modules sont des fichiers *.py
- Les packages sont des dossiers qui représentent les namespaces. Ils contiennent un fichiers __init__.py
__init__.py
|
__all__ = ["module1"]
|
POO
Classe
my_class.py
|
class MyClass(object):
""" documentation pour la classe
multi-lignes """
classAttribute = 0
def __init__(self, someValue):
""" documentation du constructeur """
self.MyAttribute = someValue
def myMethod(self, Arg1, Arg2 = 0):
self.MyAttribute = Arg1
return Arg2
@classmethod
def myClassMethod(cls):
cls.classAttribute += 1
@staticmethod
def myStaticMethod():
MaClass.classAttribute += 1
|
main.py
|
from my_class import MyClass
if __name__ == '__main__':
myObject = MyClass("Arg1")
print(dir(myObject))
print(myObject.MyAttribute)
print(myObject.classAttribute)
print(MyClass.classAttribute)
retour = myObject.myMethod("Arg2", 10)
print(myObject.MyAttribute)
print(retour)
MyClass.myClassMethod()
print(MyClass.classAttribute)
MyClass.myStaticMethod()
print(MyClass.classAttribute)
|
 |
Tous les arguments sont passés par référence |
Héritage
|
class A():
def __init__(self):
self.Attribute1 = 10
def Who(self):
print("A")
class B():
def Who(self):
print("B")
class C(A, B):
def __init__(self):
A.__init__(self)
super(B).__init__(type(self))
def Who(self):
print("B")
|
Variables globales
|
globvar = 0
def modifyGlobvar1():
globvar = 1
def modifyGlobvar2():
global globvar
globvar = 2
def printGlobvar():
print(globvar)
printGlobvar()
modifyGlobvar1()
printGlobvar()
modifyGlobvar2()
printGlobvar()
|
Création - suppression - copie
|
import os
os.rename('/dossier1/fichier1', '/dossier2/fichier2')
os.remove(r'chemin vers le fichier')
|
Lecture - écriture
|
with open('chemin vers le fichier', 'r') as fichier:
contenuFichier = fichier.read()
for line in fichier.read_lines():
fichier.write('texte')
|
|
import requests
import shutil
url = 'http://www.doamin.fr/file.zip'
local_filename = url.split('/')[-1]
r = requests.get(url, stream=True)
with open(local_filename, 'wb') as f:
shutil.copyfileobj(r.raw, f)
|
Création - suppression - copie
|
import os, shutil
os.mkdir(r'chemin vers un dossier')
shutil.rmtree(r'chemin vers le dossier')
shutil.copytree('source', 'destination')
shutil.copytree('source', 'destination', ignore=shutil.ignore_patterns('*.log', '*.py'))
|
Parcourt
|
import os, glob
folder_names = [x.name for x in os.scandir('/media/data') if x.is_dir()]
file_names = [x.path for x in os.scandir('/media/data') if x.is_file()]
for name in os.listdir('/path/folder'):
for filename in [x for x in os.listdir() if re.search('*.mp4', x)]:
for path in glob.glob(r'/chemin/vers/un/dossier/*.ext'):
for root, dirs, files in os.walk(r'chemin vers un dossier'):
|
|
import os
from os import path
if path.exists(r'chemin vers un dossier'):
if path.isfile(r'chemin vers un fichier'):
if path.isdir(r'chemin vers un dossier'):
directoryPath = path.dirname(r'chemin vers le fichier')
fileName = path.basename(r'chemin vers le fichier')
path.splitext(r'/path/file.ext')
os.getcwd()
os.chdir('/path')
path.join('/path', 'file-name.ext')
path.realpath('/path')
path.expanduser('~')
path.ismount('/path')
__file__
sys.argv[0]
|
Logger |
objet qui permet d'appeler les méthodes de log
|
Handler |
envoie le message de log vers une destination: console, fichier
|
Filter |
filtre les messages de log
|
Formatter |
décrit la mise en forme du message de log
|
|
import logging
logging.basicConfig(
format = '%(asctime)s %(levelname)s - %(filename)s,%(funcName)s,%(lineno)d: %(message)s',
datefmt = '%d/%m/%Y %H:%M:%S'
level = logging.DEBUG,
filename = 'app.log')
logging.warning('LOG !!!')
try:
except Exception, e:
logging.error('Failed', exc_info=True)
|
Handlers
Permet de loguer dans plusieurs destinations en même temps.
|
import logging.handlers
logger = logging.getLogger()
logger.setLevel(logging.NOTSET)
filehandler = logging.handlers.RotatingFileHandler('main.log', maxBytes=1024, backupCount=1)
filehandler.setLevel(logging.ERROR)
filehandler.setFormatter(
logging.Formatter(
'%(asctime)s %(levelname)s - %(name)s,%(filename)s,%(funcName)s,%(lineno)d: %(message)s',
datefmt = '%d/%m/%Y %H:%M:%S'))
logger.addHandler(filehandler)
consolehandler = logging.StreamHandler()
consolehandler.setLevel(logging.INFO)
consolehandler.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
logger.addHandler(consolehandler)
logger.error('Test !!!')
|
Loggers
Sélectionne le logger à utiliser en fonction du besoin.
|
logger = logging.getLogger(__name__)
|
Fichier de configuration
|
import yaml
with open('logging_configuration.yaml', 'rt') as f:
config = yaml.safe_load(f.read())
logging.config.dictConfig(config)
|
logging_configuration.yaml
|
version: 1
disable_existing_loggers: False
formatters:
file_formatter:
format: "%(asctime)s %(levelname)s - %(name)s,%(filename)s,%(funcName)s,%(lineno)d: %(message)s"
console_formatter:
format: "%(levelname)s - %(message)s"
handlers:
console:
class: logging.StreamHandler
level: INFO
formatter: console_formatter
stream: ext://sys.stdout
file_handler:
class: logging.handlers.RotatingFileHandler
level: ERROR
formatter: file_formatter
filename: info.log
maxBytes: 1024
backupCount: 1
encoding: utf8
root:
level: NOTSET
handlers: [console, file_handler]
|
|
pip install coloredlogs
|
logging_configuration.yaml
|
formatters:
colored_console_formatter:
(): coloredlogs.ColoredFormatter
level_styles:
debug:
color: green
verbose:
color: magenta
info:
color: cyan
warning:
color: yellow
error:
color: red
critical:
color: red
bold: True
field_styles:
hostname:
color: magenta
programname:
color: cyan
name:
color: blue
levelname:
color: white
bold: True
asctime:
color: green
format: "%(levelname)s - %(message)s"
|
Permet d'appeler les commandes bash sous forme de méthodes python.
|
from sh import pgrep
print(pgrep('firefox'))
|
|
pacman -S python-sh
|
|
import subprocess
subprocess.run(["ls", "-a", "-l"])
subprocess.run("ls -a -l", shell=True)
completedProcess = subprocess.run(["ls", "-a", "-l"], capture_output=True)
print(completedProcess.stdout.decode("utf-8"))
subprocess.run(["ls", "-l"], stdout=subprocess.DEVNULL)
completedProcess = subprocess.run("./my-script.sh")
print(completedProcess.returncode)
try:
subprocess.run("./my-script.sh", check=True)
except subprocess.CalledProcessError as e:
print(e)
|
Pipe
|
import subprocess
from subprocess import PIPE
output = subprocess.check_output("ls ~ | tail -n 3 | xargs", stderr=subprocess.STDOUT, shell=True)
ls = subprocess.Popen(['ls', '~'], stdout=PIPE, stderr=PIPE)
tail = subprocess.Popen(['tail', '-n', '3'], stdin=ls.stdout, stdout=PIPE, stderr=PIPE)
xargs = subprocess.Popen(['xargs'], stdin=tail.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = xargs.stdout.read().strip().decode("utf-8")
xargs = subprocess.run(['xargs'], stdin=tail.stdout, stdout=PIPE, stderr=PIPE)
output = xargs.stdout
|
Si le code de retour n'est pas 0, lève une CalledProcessError.
|
import subprocess
from subprocess import CalledProcessError, DEVNULL
try:
subprocess.check_call(['ping', '-c', '1', 'remote'], stdout=DEVNULL)
except CalledProcessError as e:
print(f'{e.returncode} - {e.cmd} - {e.output} - {e.stdout} - {e.stderr}')
exit(f'{e.cmd[3].upper()} is not reachable.')
|
Fichier:Py.svg
|
import json
with open('/path/file.json') as my_file:
my_dict = json.load(my_file)
my_dict = json.loads(json_content)
my_dict['my_key']
|
Fichier:Py.svg
|
while ('firefox' in (p.name() for p in psutil.process_iter())):
input('Close Firefox to continue.')
|
Équivalent de LINQ pour Python.
|
pip install asq
|
|
from asq.initiators import query
words = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"]
query(words).first(lambda w: w.startswith('f'))
|
|
from fabric import Connection
result = Connection('remote-hostname').run('ls', hide=True)
msg = "Ran {0.command!r} on {0.connection.host}, got stdout:\n{0.stdout}"
print(msg.format(result))
with Connection('remote-hostname', user='usr', password='pwd') as c:
c.get('/path/file.ext', local='/path/folder')
|
Archives
|
import zipfile
with zipfile.ZipFile(path) as z:
z.extractall()
|
|
import gzip
with gzip.open('/chemin/fichier.gz', 'rb') as f:
content_in_bytes = f.read()
content = content_in_bytes.decode("utf-8")
|
|
with open(path, newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=';')
for row in reader:
print(row)
reader = csv.DictReader(csvfile, delimiter=';')
for row in reader:
print(row['nom_colonne_1'], row['nom_colonne_5'])
|
Self-contained directory tree that contains a Python installation for a particular version of Python, plus a number of additional packages.
|
python3 -m venv --prompt '|> my-app <| ' my-env
source my-env/bin/activate
|
|
python -m venv my-env --prompt 'my-app'
\my-env\Scripts\activate
deactivate
rm -r my-env
pip freeze > requirements.txt
pip install -r requirements.txt
|
Gestionnaire de paquets pour python.
 |
Use python3 -m pip instead of pip |
|
pip search "query"
pip install [package-name]
pip uninstall [package-name]
pip install -U paquet
pip list --outdated
pip list --format=columns
find /usr/lib/python3.9/site-packages -maxdepth 2 -name __init__.py | xargs pacman -Qo | grep 'No package'
find ~/.local/lib/python3.9/site-packages -maxdepth 2 -name __init__.py | xargs pacman -Qo | grep 'No package'
find /usr/local/lib/python3.6/dist-packages -maxdepth 2 -name __init__.py | xargs realpath | xargs dpkg -S 2>&1 | grep 'no path found'
pip show [package_name]
pipdeptree
pipdeptree --reverse --packages [package_name]
|
 |
Ubuntu:
Les paquets sont téléchargés dans $HOME/.cache/pip
Les paquets sont installés dans $HOME/.local/lib/pythonX.X/site-packages ou /usr/local/lib/pythonX.X/dist-packages |
 |
ArchLinux:
Les paquets à installer se nomment python-pip ou python2-pip
Et les commandes sont pip ou pip2.
Les paquets sont installés dans ~/.local/lib/pythonX.X/site-packages ou /usr/lib/pythonX.X/site-packages
Les exécutables sont installés dans ~/.local/bin ou /usr/bin ? |
requirements.txt
|
pip freeze > requirements.txt
pip install -r requirements.txt
|
Erreurs
Désinstaller la version pip du système et installer celle fournie par pypa.
|
pip3 install --upgrade pip
|
Safe and easy pip package manager. Automatically install packages into python environments to not mess up with system packages.
 |
Add /usr/local/bin to your PATH |
|
sudo -H pip-safe --system install <package>
pip-safe list
sudo mkdir -p /opt/pip-safe
sudo chown [current-user]:[current-group] /opt/pip-safe
python3 -m venv /opt/pip-safe/pip-safe
/opt/pip-safe/pip-safe/bin/pip install pip-safe
sudo chown root:root -R /opt/pip-safe
sudo ln -s /opt/pip-safe/pip-safe/bin/pip-safe /usr/local/bin/pip-safe
|