This commit is contained in:
2019-05-12 16:17:58 +02:00
parent 941984f1ee
commit afc8ff0845
24 changed files with 945 additions and 35 deletions

4
docs/Linux/ack.md Normal file
View File

@@ -0,0 +1,4 @@
# ack

View File

@@ -117,3 +117,35 @@ $ usermod -G "" <username>
```
### Code de sortie:
Chaque commande renvoie un *code de sortie* (quelque fois nommé *état de retour* ).
Une commande ayant réussi renvoie un 0.
Une commande ayant échoué renvoie une valeur différente de zéro qui est habituellement interprétable comme un code d'erreur.
De même, les fonctions dans un script et le script lui-même renvoient un code de sortie. La dernière commande exécutée dans la fonction ou le script détermine le code de sortie.
À l'intérieur d'un script, une commande **exit nnn** peut être employée pour retourner un code de sortie *nnn* au shell (*nnn* doit être un nombre décimal compris entre 0 et 255).
```bash
$ hostname
silverbook.home
$ echo $?
0
$ hostnam
-bash: hostnam: command not found
$ echo $?
127
```
```bash
$ hostname
silverbook.home
bruno@SilverBook:~/.kymsu/plugins.d$ if [ $? -eq 0 ]; then echo "ok"; else echo "nok"; fi
ok
```

View File

@@ -26,6 +26,12 @@ else
fi
```
### if (one-line)
```bash
if [ "$choice" == "72" ]; then echo "sphp 72"; elif [ "$choice" == "73" ]; then echo "sphp 73"; fi
```
### if imbriqué

View File

@@ -5,7 +5,7 @@
#### 1ere syntaxe:
```bash
bash for variable in liste_valeurs
for variable in liste_valeurs
do instruction(s)
done
```

View File

@@ -36,6 +36,14 @@ grep -l -r "brew" ./docs/
<u>Chercher dans tous les fichiers 'php' ou 'html' (et ignorer les dossiers '.git'):</u>
```bash
grep pattern $(find . -name '*.php' -or -name '*.html' | grep -v .git)
```
<u>Regex:</u>
```bash

View File

@@ -1,6 +1,6 @@
# class
# Les classes

View File

@@ -33,6 +33,18 @@ C'est une collection **non ordonnée**, **modifiable** et **indexée**.
{'marque': 'Ford', 'modele': 'Mustang', 'annee': 1964}
```
```python
# Liste l de couples transformée en dictionnaire
>>> l = [('a',1), ('b',2)]
>>> dict(l)
{'a': 1, 'b': 2}
```
```python
>>> dict(zip('abc',range(3)))
{'a': 0, 'b': 1, 'c': 2}
```
##### Accéder à un item:
```python
@@ -82,6 +94,15 @@ C'est une collection **non ordonnée**, **modifiable** et **indexée**.
{'language': 'python', 'version': '3.7'}
```
##### Ajouter des valeurs (update):
```python
>>> d = {'a':0}
>>> d.update(zip('bcd',range(1,4)))
>>> d
{'a': 0, 'b': 1, 'c': 2, 'd': 3}
```
##### Vérifier la présence d'une clé (in):
```python
@@ -181,7 +202,7 @@ language python
version 3.7
```
Vérifier si une clé existe dans un dictionnaire:
##### Vérifier si une clé existe dans un dictionnaire:
```python
>>> dict = {'language': 'python', 'version': '3.7'}
@@ -191,7 +212,7 @@ Vérifier si une clé existe dans un dictionnaire:
'language' est dans dict
```
Longueur d'un dictionnaire:
##### Longueur d'un dictionnaire:
```python
>>> dict = {'language': 'python', 'version': '3.7'}
@@ -199,33 +220,96 @@ Longueur d'un dictionnaire:
2
```
##### Copier un dictionnaire (copy):
```python
>>> autre_dict = dict.copy()
>>> autre_dict
{'language': 'python', 'version': '3.7'}
>>> autre_dict['language'] = 'PYTHON'
>>> autre_dict
{'language': 'PYTHON', 'version': '3.7'}
>>> dict
{'language': 'python', 'version': '3.7'}
```
##### Fromkeys():
```python
>>> d3 = {}
>>> d3 = {}.fromkeys('abcde', 0)
>>> d3
{'a': 0, 'b': 0, 'c': 0, 'd': 0, 'e': 0}
```
#### Méthodes:
| Méthode | Description |
| ------------ | ----------- |
| clear() | |
| copy() | |
| fromkeys() | |
| get() | |
| items() | |
| keys() | |
| pop() | |
| popitem() | |
| setdefault() | |
| update() | |
| values() | |
| -------------------- | ------------------------------------------------------------ |
| d.clear() | supprime tous les éléments de `d` |
| d.copy() | shallow copie de `d` |
| {}.fromkeys(s,v) | créée un dict avec les clés de `s` et la valeur `v` |
| d.get(k [,v]) | envoie la valeur `d[k]` si elle existe v sinon |
| d.items() | liste des items `(k,v)` de `d` |
| d.keys() | liste des clés |
| d.pop(k [,v]) | enlève `d[k]` sil existe et renvoie sa valeur ou `v` sinon |
| d.popitem() | supprime un item `(k,v)` et retourne litem sous forme de tuple |
| d.setdefault(k [,v]) | `d[k]` si elle existe sinon `v` et rajoute `d[k] = v` |
| d.update(s) | `s` est une liste de tuples que lon rajoute à `d` |
| d.values() | liste des valeurs de `d` |
#### Dictionnaires persistants:
Python permet de créer des dictionnaires persistants, grâce au module `shelve`.
`shelve` fournit une solution de persistance de type “base de données” très simple qui sera gérée automatiquement dans un fichier.
La méthode `shelve.open('f')` crée dans le répertoire courant de votre ordinateur, un fichier de sauvegarde “f.db” sil nexiste pas, et retourne un objet de type `shelve` ; un `shelve` fonctionne comme un dictionnaire. La plupart des opérations et méthodes des dictionnaires lui sont applicables ; toute modification appliquée au `shelve` est automatiquement sauvegardée. La méthode `shelve.close` permet de fermer le `shelve`, comme pour un fichier.
```python
>>> import shelve
>>> t = [0,1,2,3,4,5,6,7]
>>> p = (1,2,3)
>>> i = 23
>>> s = 'Bonjour'
>>> db = shelve.open('data')
>>> db['liste'] = t
>>> db['point'] = p
>>> db['entier'] = i
>>> db['chaine'] = s
>>> print(dict(db))
{'point': (1, 2, 3), 'entier': 23, 'liste': [0, 1, 2, 3, 4, 5, 6, 7], 'chaine': 'Bonjour'}
>>> db.close()
>>> exit()
~$ ls -la
-rw-r--r-- 1 bruno staff 16384 25 mar 08:55 data
# On relance une session Python
>>> import shelve
>>> with shelve.open('data') as db:
... print(db['liste'])
... for k in db:
... print(db[k])
...
[0, 1, 2, 3, 4, 5, 6, 7]
(1, 2, 3)
23
[0, 1, 2, 3, 4, 5, 6, 7]
Bonjour
```
Si votre code modifie plusieurs fois certaines entrées lors de la même session, lors de louverture du `shelve`, il est important, dans la méthode `open` associée au `shelve`, de mettre le paramètre `writeback` à vrai, comme suit :
```python
shelve.open('data', writeback=True)
```
Grâce à cette option, chaque fois quune modification est réalisée au `shelve`, cette modification est correctement répercutée sur la mémoire morte (le disque dur) de votre ordinateur.

View File

@@ -38,7 +38,23 @@ Parcourrir un fichier ligne par ligne:
>>> for x in fichier:
... print(x)
...
```
```python
>>> with open("pecl-help.txt") as fichier:
... for line in fichier:
... print(line, end='')
...
```
Ouverture d'un fichier binaire:
```python
>>> with open('file', 'rb') as fichierbinaire:
... octets = fichierbinaire.read() # le fichier est lu en entier
... print("on a lu un objet de type", type(octets))
... for i, octet in enumerate(octets):
... print(f"{i}{repr(chr(octet))} [{hex(octet)}]")
```
@@ -56,8 +72,8 @@ fichier.close()
##### Type d'ouverture:
```python
r, pour une ouverture en lecture (READ).
w, pour une ouverture en écriture (WRITE), à chaque ouverture le contenu du fichier est écrasé. Si le fichier n'existe pas python le crée.
r, pour une ouverture en lecture (READ). (Par défaut)
w, pour une ouverture en écriture (WRITE), à chaque ouverture le contenu du fichier est écrasé. Si le fichier n'existe pas, Python le crée.
a, pour une ouverture en mode ajout à la fin du fichier (APPEND). Si le fichier n'existe pas python le crée.
b, pour une ouverture en mode binaire.
t, pour une ouverture en mode texte.
@@ -92,7 +108,7 @@ if os.path.exists("empty_folder"):
#### Chemins
#### Chemins (os.path)
##### Méthodes:
@@ -206,3 +222,37 @@ os.rename(old, new) → Renomme le fichier / dossier indiqué
#### pathlib
Depuis Python 3.4, le module `os.path` est obsolète et est remplacé par la librairie `pathlib`.
```python
from pathlib import Path
help(pathlib)
```
```python
from pathlib import Path
filename = 'scratch.py'
path = Path(filename)
if path.exists():
print("existe")
print(path.stat().st_size) # taille
print(path.stat().st_mtime) # dernière modif
try:
path.unlink()
except FileNotFoundError:
print("Pas de fichier à supprimer")
```
```python
from pathlib import Path
dirpath = Path('.') # répertoire courant
for py in dirpath.glob("*.py"):
print(py) # liste des fichiers Python du répertoire courant
```

View File

@@ -0,0 +1,65 @@
# For
##### Range:
```python
>>> somme = 0
>>> for i in range(10):
... somme += i
...
>>> print(somme)
45
```
##### Parcourir une liste:
```python
>>> thislist = ["alpha", "beta", "gamma"]
>>> for elem in thislist:
... print(elem)
...
alpha
beta
gamma
```
##### Parcourir une chaine:
```python
>>> language = "Python"
>>> for c in language:
... print("Caractère : ", c)
...
Caractère : P
Caractère : y
Caractère : t
Caractère : h
Caractère : o
Caractère : n
```
##### Parcourir une chaine par les indices:
```python
>>> language = "Python"
>>> for i in range(len(language)):
... print("Caractère d'indice",i," :",language[i])
...
Caractère d'indice 0 : P
Caractère d'indice 1 : y
Caractère d'indice 2 : t
Caractère d'indice 3 : h
Caractère d'indice 4 : o
Caractère d'indice 5 : n
```
##### Plusieurs variables dans une boucle for:
```python
entrees = [(1, 2), (3, 4), (5, 6)]
for a, b in entrees:
print(f"a={a} b={b}")
```

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

View File

@@ -0,0 +1,209 @@
# In
##### Test si un item est présent dans une liste:
```python
>>> language = ["Python", "Perl", "C++"]
>>> i = "Python"
>>> if i in language:
... print("Python appartient à language")
...
Python appartient à language
```
##### Test si une liste est présent dans une autre liste:
```python
>>> liste1 = [9,18,3,5,7,21]
>>> liste2 = [9,18,[3,5,7],21]
>>> [3,5,7] in liste1
False
>>> [3,5,7] in liste2
True
```
##### Test su une séquence est présent dans une chaine:
```python
>>> language = "Python"
>>> 'thon' in language
True
```
### Slicing:
##### Sous-séquence:
```python
>>> str = "Bonjour, ça va ?"
>>> str[1:3]
'on'
>>> str[:3]
'Bon'
>>> str[3:]
'jour, ça va ?'
```
##### Copie de séquence:
```python
>>> prem = [1,2,3,5,7]
>>> sec = prem[:]
>>> sec
[1, 2, 3, 5, 7]
```
##### Pas:
```python
>>> language = "Python"
>>> language[::2]
'Pto'
# On prend 1 lettre sur 2
>>> language[::-1]
'nohtyP'
# On part de la fin
```
##### Gestion mémoire des séquences:
```python
>>> prem = [2, 3]
>>> prem = sec = [2, 3]
>>> id(prem)
4468993928
>>> id(sec)
4468993928
>>> trois = [2, 3]
>>> id(trois)
4468967496
>>> prem is sec
True
>>> prem is trois
False
>>> prem == trois
True
>>> prem.append(5)
>>> prem
[2, 3, 5]
>>> sec
[2, 3, 5]
>>> trois
[2, 3]
```
```python
1 prem = sec = [1, 3]
2 trois = [1, 3]
3 prem[0] = 2
4 prem.append(5)
5 prem.extend([7, 11])
6 t = 'Bonjour'
7 t2 = 'B' + t[1:]
```
![image-20190317181121361](image-20190317181121361.png)
```python
>>> tex = "bonjour"
>>> prem = [2, 3, 5, 7, 8, 9, 10, 17]
>>> prem[4:7] = [11, 13] # on remplace les éléments 4 à 7 exclu
>>> prem
[2, 3, 5, 7, 11, 13, 17]
```
#### Pack / Unpack:
```python
>>> tp = 2, 3, 5 # on crée un tuple
>>> type(tp)
<class 'tuple'>
>>> x, y, z = tp # les 3 variables x, y, z prennent les valeurs des 3 éléments du tuple
>>> x
2
>>> y
3
>>> z
5
```
```python
>>> x, y = 33, 666
>>> x, y = y, x # permutation
>>> x
666
>>> y
33
```
##### Lecture et initialisation dune chaîne de caractères:
```python
>>> s = input()
4
>>> s
'4'
>>> type(s)
<class 'str'>
```
##### Lecture et initialisation dun tuple de valeurs:
```python
>>> eval("2 + 2")
4
>>> t = eval(input())
2, 3, 4, 5
>>> t
(2, 3, 4, 5)
>>> type(t)
<class 'tuple'>
>>> t = eval(input())
"alpha", "beta", "gamma"
>>> t
('alpha', 'beta', 'gamma')
>>> type(t)
<class 'tuple'>
```
##### Création d'une séquence à partir d'une autre:
```python
>>> t = (1, 2, 3, 4)
>>> t
(1, 2, 3, 4) # tuple
>>> l = list(t)
>>> l
[1, 2, 3, 4] # liste
>>> l = list("Bonjour") # str
>>> l
['B', 'o', 'n', 'j', 'o', 'u', 'r'] # liste
```

View File

@@ -3,10 +3,10 @@
1. collections:
1. [liste](liste.md)
2. [dictionnaire](dictionnaire.md)
3. [tuple](tuple.md)
4. [set](set.md)
1. [liste []](liste.md)
2. [dictionnaire {}](dictionnaire.md)
3. [tuple ()](tuple.md)
4. [set {}](set.md)
2. [class - objet](class.md)
3. [date](date.md)
4. [fichiers](fichiers.md)
@@ -25,6 +25,16 @@ https://www.w3schools.com/python/default.asp
| Hashable (non modifiable) | Unhashable |
| ------------------------- | --------------- |
| int | liste [] |
| float | set {} |
| bool | dictionnaire {} |
| str | |
| tuples () | |
#### Instruction de boucles
##### while:

View File

@@ -0,0 +1,26 @@
# json
```python
import json
# En partant d'une donnée construite à partir de types de base
data = [
# des types qui ne posent pas de problème
[1, 2, 'a', [3.23, 4.32], {'eric': 32, 'jean': 43}],
# un tuple
(1, 2, 3),
]
# sauver ceci dans un fichier
with open("s1.json","w", encoding='utf-8') as json_output:
json.dump(data, json_output)
# et relire le résultat
with open("s1.json", encoding='utf-8') as json_input:
data2 = json.load(json_input)
```

View File

@@ -251,6 +251,11 @@ False
>>> a.extend(b)
>>> print(a)
[1, 2, 3, 4, 5, 6]
>>> a.extend([7, 8, 9])
>>> print(a)
[1, 2, 3, 7, 8, 9]
>>> c = a + b
>>> print(c)
[1, 2, 3, 4, 5, 6, 4, 5, 6]
@@ -272,6 +277,21 @@ if "alpha" in thislist:
print("Oui, 'alpha' est dans la liste")
```
##### Liste d'éléments de types différents:
```python
>>> s = [1, 3, 3.14, ("bon","jour"), [5, 7]]
>>> len(s)
5
>>> len(s[3]) # tuple
2
>>> len(s[3][1]) # tuple - str "jour"
4
>>> s[4][1] = 666 # sous-liste - int 7
>>> s
[1, 3, 3.14, ('bon', 'jour'), [5, 666]]
```
#### Méthodes:

View File

@@ -0,0 +1,170 @@
# Requests
https://realpython.com/python-requests/
https://realpython.com/caching-external-api-requests/
```bash
pip3 install requests
```
#### Requête GET:
```python
>>> import requests
>>> requests.get('https://api.github.com')
<Response [200]>
>>> requests.get('https://api.github.com', timeout=1)
<Response [200]>
# nb de second avant un timeout
```
##### Status Code:
```python
>>> response = requests.get('https://api.github.com')
>>> print(response)
<Response [200]>
>>> response.status_code
200
>>> if response.status_code == 200:
... print('Success!')
... elif response.status_code == 404:
... print('Not Found.')
...
Success!
```
```python
import requests
from requests.exceptions import HTTPError
for url in ['https://api.github.com', 'https://api.github.com/invalid']:
try:
response = requests.get(url)
# If the response was successful, no Exception will be raised
response.raise_for_status()
except HTTPError as http_err:
print(f'HTTP error occurred: {http_err}') # Python 3.6
except Exception as err:
print(f'Other error occurred: {err}') # Python 3.6
else:
print('Success!')
# la 1ere url répond par un Success
# la 2nde par une erreur
```
##### Content:
```python
# bytes
>>> response.content
b'{"current_user_url":"https://api.github.com/user","current_user_authorizations_html_url":"https://github.com/settings/connections/applications{/client_id}","authorizations_url":"https://api.github.com/authorizations","code_search_url":"https://api.github.com/search/code?q={query}{&page,per_page,sort,order}","commit_search_url":"https://api.github.com/search/commits?q={query}{&page,per_page,sort,order}","emails_url":"https://api.github.com/user/emails","emojis_url":"https://api.github.com/emojis","events_url":"https://api.github.com/events","feeds_url":"https://api.github.com/feeds","followers_url":"https://api.github.com/user/followers","following_url":"https://api.github.com/user/following{/target}","gists_url":"https://api.github.com/gists{/gist_id}","hub_url":"https://api.github.com/hub","issue_search_url":"https://api.github.com/search/issues?q={query}{&page,per_page,sort,order}","issues_url":"https://api.github.com/issues","keys_url":"https://api.github.com/user/keys","notifications_url":"https://api.github.com/notifications","organization_repositories_url":"https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}","organization_url":"https://api.github.com/orgs/{org}","public_gists_url":"https://api.github.com/gists/public","rate_limit_url":"https://api.github.com/rate_limit","repository_url":"https://api.github.com/repos/{owner}/{repo}","repository_search_url":"https://api.github.com/search/repositories?q={query}{&page,per_page,sort,order}","current_user_repositories_url":"https://api.github.com/user/repos{?type,page,per_page,sort}","starred_url":"https://api.github.com/user/starred{/owner}{/repo}","starred_gists_url":"https://api.github.com/gists/starred","team_url":"https://api.github.com/teams","user_url":"https://api.github.com/users/{user}","user_organizations_url":"https://api.github.com/user/orgs","user_repositories_url":"https://api.github.com/users/{user}/repos{?type,page,per_page,sort}","user_search_url":"https://api.github.com/search/users?q={query}{&page,per_page,sort,order}"}'
# string
>>> response.encoding = 'utf-8'
>>> response.text
# JSON
>>> response.json()
{'current_user_url': 'https://api.github.com/user', 'current_user_authorizations_html_url': 'https://github.com/settings/connections/applications{/client_id}', 'authorizations_url': 'https://api.github.com/authorizations', 'code_search_url': 'https://api.github.com/search/code?q={query}{&page,per_page,sort,order}', 'commit_search_url': 'https://api.github.com/search/commits?q={query}{&page,per_page,sort,order}', 'emails_url': 'https://api.github.com/user/emails', 'emojis_url': 'https://api.github.com/emojis', 'events_url': 'https://api.github.com/events', 'feeds_url': 'https://api.github.com/feeds', 'followers_url': 'https://api.github.com/user/followers', 'following_url': 'https://api.github.com/user/following{/target}', 'gists_url': 'https://api.github.com/gists{/gist_id}', 'hub_url': 'https://api.github.com/hub', 'issue_search_url': 'https://api.github.com/search/issues?q={query}{&page,per_page,sort,order}', 'issues_url': 'https://api.github.com/issues', 'keys_url': 'https://api.github.com/user/keys', 'notifications_url': 'https://api.github.com/notifications', 'organization_repositories_url': 'https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}', 'organization_url': 'https://api.github.com/orgs/{org}', 'public_gists_url': 'https://api.github.com/gists/public', 'rate_limit_url': 'https://api.github.com/rate_limit', 'repository_url': 'https://api.github.com/repos/{owner}/{repo}', 'repository_search_url': 'https://api.github.com/search/repositories?q={query}{&page,per_page,sort,order}', 'current_user_repositories_url': 'https://api.github.com/user/repos{?type,page,per_page,sort}', 'starred_url': 'https://api.github.com/user/starred{/owner}{/repo}', 'starred_gists_url': 'https://api.github.com/gists/starred', 'team_url': 'https://api.github.com/teams', 'user_url': 'https://api.github.com/users/{user}', 'user_organizations_url': 'https://api.github.com/user/orgs', 'user_repositories_url': 'https://api.github.com/users/{user}/repos{?type,page,per_page,sort}', 'user_search_url': 'https://api.github.com/search/users?q={query}{&page,per_page,sort,order}'}
# retourne un dictionnaire
```
##### Headers:
```python
>>> response.headers
{'Server': 'GitHub.com', 'Date': 'Fri, 29 Mar 2019 15:32:44 GMT', 'Content-Type': 'application/json; charset=utf-8', 'Transfer-Encoding': 'chunked', 'Status': '200 OK', 'X-RateLimit-Limit': '60', 'X-RateLimit-Remaining': '59', 'X-RateLimit-Reset': '1553877164', 'Cache-Control': 'public, max-age=60, s-maxage=60', 'Vary': 'Accept', 'ETag': 'W/"7dc470913f1fe9bb6c7355b50a0737bc"', 'X-GitHub-Media-Type': 'github.v3; format=json', 'Access-Control-Expose-Headers': 'ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type', 'Access-Control-Allow-Origin': '*', 'Strict-Transport-Security': 'max-age=31536000; includeSubdomains; preload', 'X-Frame-Options': 'deny', 'X-Content-Type-Options': 'nosniff', 'X-XSS-Protection': '1; mode=block', 'Referrer-Policy': 'origin-when-cross-origin, strict-origin-when-cross-origin', 'Content-Security-Policy': "default-src 'none'", 'Content-Encoding': 'gzip', 'X-GitHub-Request-Id': 'B245:1134:87E5:14D2A:5C9E3A9C'}
# retourne un dictionnaire
>>> response.headers['Content-Type']
'application/json; charset=utf-8'
```
##### Query strings parameters:
```python
import requests
# Search GitHub's repositories for requests
response = requests.get(
'https://api.github.com/search/repositories',
params={'q': 'requests+language:python'},
)
# Inspect some attributes of the `requests` repository
json_response = response.json()
repository = json_response['items'][0]
print(f'Repository name: {repository["name"]}') # Python 3.6+
print(f'Repository description: {repository["description"]}') # Python 3.6+
Repository name: requests
Repository description: Python HTTP Requests for Humans 🍰
```
##### Autres méthodes HTTP:
```python
>>> requests.post('https://httpbin.org/post', data={'key':'value'})
>>> requests.put('https://httpbin.org/put', data={'key':'value'})
>>> requests.delete('https://httpbin.org/delete')
>>> requests.head('https://httpbin.org/get')
>>> requests.patch('https://httpbin.org/patch', data={'key':'value'})
>>> requests.options('https://httpbin.org/get')
```
#### Requête POST:
```python
>>> requests.post('https://httpbin.org/post', data={'key':'value'})
<Response [200]>
```
```python
>>> response = requests.post('https://httpbin.org/post', json={'key':'value'})
>>> json_response = response.json()
>>> json_response['data']
'{"key": "value"}'
>>> json_response['headers']['Content-Type']
'application/json'
```
```python
>>> response = requests.post('https://httpbin.org/post', json={'key':'value'})
>>> response.request.headers['Content-Type']
'application/json'
>>> response.request.url
'https://httpbin.org/post'
>>> response.request.body
b'{"key": "value"}'
```
Authentification:
```python
>>> from requests.auth import HTTPBasicAuth
>>> from getpass import getpass
>>> requests.get(
... 'https://api.github.com/user',
... auth=HTTPBasicAuth('bruno@xxxxx.info', getpass())
... )
Password:
<Response [200]>
```

View File

@@ -1,8 +1,8 @@
# Set
# Set (ensemble)
Une liste est une collection **non ordonnée** et **non indexée**. On ne peut pas modifier un item, mais on peut en ajouter.
Un set est une collection **non ordonnée** et **non indexée**. On ne peut pas modifier un item, mais on peut en ajouter.
@@ -12,6 +12,17 @@ Une liste est une collection **non ordonnée** et **non indexée**. On ne peut p
>>> un_set = {"alpha", "beta", "gamma"}
>>> un_set
{'alpha', 'beta', 'gamma'}
>>> type(un_set)
<class 'set'>
```
```python
>>> autre_set = {"alpha", "beta", "gamma", "beta", "alpha"}
>>> len(autre_set)
3
>>> autre_set
{'beta', 'alpha', 'gamma'}
```
```python
@@ -54,6 +65,12 @@ Une liste est une collection **non ordonnée** et **non indexée**. On ne peut p
>>> un_set.remove("beta")
>>> un_set
{'gamma', 'alpha'}
# Si on retire un élément qui n'existe pas => Erreur
>>> un_set.remove("delta")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'delta'
```
##### Supprimer un item (discard):
@@ -63,6 +80,12 @@ Une liste est une collection **non ordonnée** et **non indexée**. On ne peut p
>>> un_set.discard("beta")
>>> un_set
{'gamma', 'alpha'}
# Si on retire un élément qui n'existe pas.
>>> un_set = {"alpha", "beta", "gamma"}
>>> un_set.discard("delta")
>>> un_set
{'alpha', 'gamma', 'beta'}
```
##### Vider un set:
@@ -105,6 +128,23 @@ print("alpha" in un_set)
True
```
##### Set => pas d'indice:
```python
>>> un_set = {"alpha", "beta", "gamma"}
>>> un_set[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'set' object does not support indexing
```
##### Opérateurs:
- `a | b` (union),
- `a & b` (intersection),
- `a - b` (différence),
- `a ^ b` (différence symétrique)
#### Méthodes:

View File

@@ -2,6 +2,51 @@
```python
>>> mon_str = "bonjour"
>>> print(mon_str)
bonjour
>>> long_str = """***********
... * Bonjour *
... ***********
... """
>>> long_str
'***********\n* Bonjour *\n***********\n'
>>> print(long_str)
***********
* Bonjour *
***********
```
```python
# Concaténation
>>> mon_str + " Bruno"
'bonjour Bruno'
# Répétition
>>> "ha " * 5
'ha ha ha ha ha '
# Longueur de la chaine
>>> len(mon_str)
7
# Indice
>>> mon_str[0]
'b'
>>> mon_str[6]
'r'
>>> mon_str[len(mon_str)-1]
'r'
>>> mon_str[-1]
'r'
>>> mon_str[-3]
'o'
```
##### str.count()
```python

View File

@@ -0,0 +1,39 @@
# zip
La fonction `zip` associe 2 listes et retourne une liste de tuples.
```python
villes = ["Paris", "Rome", "Göteborg"]
pays = ["France", "Italie", "Suède"]
print(list(zip(villes, pays)))
for ville, etat in zip(villes, pays):
print(ville, " est la capitale de ", etat)
[('Paris', 'France'), ('Rome', 'Italie'), ('Göteborg', 'Suède')]
Paris est la capitale de France
Rome est la capitale de Italie
Göteborg est la capitale de Suède
```
Si le nombre d'item diffère:
```python
villes = ["Paris", "Rome", "Göteborg"]
pays = ["France", "Italie", "Suède", "Suisse"]
print(list(zip(villes, pays)))
for ville, etat in zip(villes, pays):
print(ville, " est la capitale de ", etat)
[('Paris', 'France'), ('Rome', 'Italie'), ('Göteborg', 'Suède')]
Paris est la capitale de France
Rome est la capitale de Italie
Göteborg est la capitale de Suède
```

View File

@@ -86,6 +86,8 @@ $ brew cask home
### Aller à la page du Cask:
```bash
$ brew cask home {{cask_name}}
$ brew cask home qlstephen
```
@@ -102,6 +104,17 @@ $ brew cask outdated
### Version du Cask:
```bash
$ brew cask _stanza version {{cask_name}}
$ brew cask _stanza version bettertouchtool
2.800
```
### Installer les mises-à-jour:
```bash

View File

@@ -293,6 +293,15 @@ $ brew uses x264 --installed
ffmpeg
```
```bash
$ brew list -1 | while read cask; do echo -ne "\x1B[1;34m $cask \x1B[0m"; brew uses $cask --installed | awk '{printf(" %s ", $0)}'; echo ""; done
ack
aom ffmpeg
apr apr-util httpd php php@7.2
.../...
x264 ffmpeg
```
### Outils:

View File

@@ -150,6 +150,39 @@ Verify cache contents verified 2159 tarballs
#### Info sur un package:
```bash
$ npm show cli
# idem:
# npm info cli
# npm view cli
cli@1.0.1 | MIT | deps: 2 | versions: 59
A tool for rapidly building command line apps
http://github.com/node-js-libs/cli
keywords: cli, command line, opts, parseopt, opt, args, console, argsparse, optparse, autocomplete, command, autocompletion
dist
.tarball: https://registry.npmjs.org/cli/-/cli-1.0.1.tgz
.shasum: 22817534f24bfa4950c34d532d48ecbc621b8c14
dependencies:
exit: 0.1.2 glob: ^7.1.1
maintainers:
- cohara87 <cohara87@gmail.com>
dist-tags:
latest: 1.0.1
published over a year ago by cohara87 <cohara87@gmail.com>
```
#### Packages:
[Rechercher un package](https://npms.io)

View File

@@ -72,7 +72,9 @@ pip --no-cache-dir install mkdocs
### Installer un module (mkdocs):
### Installer des modules:
#### Installer un module pour l'utilisateur courant (mkdocs):
```bash
$ pip install --user mkdocs
@@ -84,7 +86,7 @@ Les modules sont ici:
### Désinstaller un module:
#### Désinstaller un module:
```bash
$ pip uninstall <module>
@@ -92,7 +94,7 @@ $ pip uninstall <module>
### Installer une ancienne version d'un module:
#### Installer une version précise d'un module:
```bash
$ pip3 show tornado
@@ -109,12 +111,15 @@ Installing collected packages: tornado
Successfully installed tornado-4.5.3
$ pip3 install 'tornado>=4.1.0,<4.5.3'
# Installe une version comprise entre 4.1.0 et 4.5.3
$ pip3 install 'tornado~=4.5.2'
# Installe une version “==4.5.*” qui est aussi “>=4.5.2”.
```
### Informations sur un module:
#### Informations sur un module:
```bash
$ pip show <module>
@@ -133,7 +138,15 @@ Requires: tornado, PyYAML, click, Markdown, Jinja2, livereload
### Liste des modules installés:
#### Installer une liste de modules requis:
```bash
$ pip install -r requirements.txt
```
#### Liste des modules installés:
```bash
# --format=columns (par defaut)
@@ -178,7 +191,9 @@ $ pip install <nom_du_bundle>.pybundle
### Liste des modules mis-à-jour:
### Mise-à-jour:
#### Liste des modules mis-à-jour:
```bash
$ pip list --outdated --format=columns
@@ -225,7 +240,7 @@ $ pip3 list --outdated --format=json
### Mettre à jour un module:
#### Mettre à jour un module:
```bash
$ pip install --user --upgrade <module>

View File

@@ -2,6 +2,8 @@
### venv
On crée un dossier pour regrouper tous les environnements virtuels:
```bash
@@ -138,3 +140,16 @@ Le module installé dans l'environnement virtuel est disponible UNIQUEMENT dans
[https://docs.python.org/fr/3/library/venv.html](https://docs.python.org/fr/3/library/venv.html)
### pyvenv
#### Installer des modules pour un projet:
```bash
cd myproject
pipenv install requests
```

View File

@@ -58,6 +58,7 @@ nav:
- Django: macos/python/Django.md
- pip: macos/python/pip.md
- Python 3: macos/python/python3.md
- Environnement virtuel: macos/python/virtuel.md
- Sécurité (Gatekeeper): macos/securite.md
- ssh:
- SSH: macos/ssh/ssh.md
@@ -88,6 +89,22 @@ nav:
- Plesk Onyx:
- Index: Plesk/index.md
- Ghost: Plesk/Ghost.md
- Programmation:
-Python:
- Index: Programmation/Python/index.md
- Classes: Programmation/Python/class.md
- Date: Programmation/Python/date.md
- Dictionnaire: Programmation/Python/dictionnaire.md
- Fabric SSH Python: Programmation/Python/fabric-ssh.md
- Fichiers: Programmation/Python/fichiers.md
- Fonctions: Programmation/Python/fonctions.md
- Boucle For: Programmation/Python/for.md
- In: Programmation/Python/in.md
- Listes: Programmation/Python/liste.md
- Les regex: Programmation/Python/regex.md
- Sets: Programmation/Python/set.md
- Strings: Programmation/Python/string.md
- Tuples: Programmation/Python/tuple.md
- Raspberry:
- Index: Raspberry/index.md
- apt-get: Raspberry/apt-get.md