Outils pour utilisateurs

Outils du site


tech:python-draft

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentesRévision précédente
tech:python-draft [2025/04/15 17:15] Jean-Baptistetech:python-draft [2025/05/26 18:56] (Version actuelle) Jean-Baptiste
Ligne 1: Ligne 1:
 +<!DOCTYPE markdown>
 +{{tag>Code Python}}
 +
 +# Draft Python3
 +
 +## List comprehensions and generator expressions
 +
 + (short form: “listcomps” and “genexps”)
 +
 +~~~python
 +line_list = ['  line 1\n', 'line 2  \n', ' \n', '']
 +
 +# Generator expression -- returns iterator
 +stripped_iter = (line.strip() for line in line_list)
 +
 +# List comprehension -- returns list
 +stripped_list = [line.strip() for line in line_list]
 +
 +stripped_list = [line.strip() for line in line_list if line != ""]
 +~~~
 +
 +
 +### Autres
 +
 +~~~python
 +def inc(f, id):
 +    """ Exemple : inc(lambda x : x+1, 0) """
 +    try :
 +        global counter
 +        counter = f(counter)
 +    except NameError:
 +        counter = 0
 +    return counter
 +~~~
 +
 +------------
 +
 +http://mgautier.fr/blog/Astuce/changer-lenvironnement-bash-avec-python.html
 +
 +------------
 +
 +## List unique remove duplicate
 +
 +Source : 
 +http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so
 +
 +~~~python
 +def unique(items):
 +    found = set([])
 +    keep = []
 +    for item in items:
 +        if item not in found:
 +            found.add(item)
 +            keep.append(item)
 +    return keep
 +~~~
 +
 +------------
 +
 +## How do you split a list into evenly sized chunks in Python?
 +
 +Source : http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python
 +
 +~~~python
 +def chunks(l, n):
 +    n = max(1, n)
 +    return [l[i:i + n] for i in range(0, len(l), n)]
 +~~~
 +
 +-------------
 +
 +## Determine if variable is defined in Python
 +
 +http://stackoverflow.com/questions/1592565/determine-if-variable-is-defined-in-python
 +
 +~~~python
 +try:
 +  thevariable
 +except NameError:
 +  print "well, it WASN'T defined after all!"
 +else:
 +  print "sure, it was defined."
 +~~~
 +
 +I think it's better to avoid the situation. It's cleaner and clearer to write:
 +
 +~~~python
 +a = None
 +if condition:
 +    a = 42
 +~~~
 +
 +------------
 +
 +## Getting file size in Python
 +
 +http://stackoverflow.com/questions/6591931/getting-file-size-in-python
 +
 +~~~python
 +def get_Size(file):
 +    file.seek(0,2) # move the cursor to the end of the file
 +    size = file.tell()
 +    return size
 +~~~
 +
 +Exemple :
 +~~~python
 +with open('plop.bin','rb') as file:
 +    size=get_Size(file)
 +
 +with open('plop.bin','rb') as file:
 +    #size=get_Size(file)
 +    for i in range(size):
 +        un, deux = read_hexafile()
 +        msg.append(un)
 +        msg.append(deux)
 +~~~
 +
 +
 +''/dev/null''
 +~~~python
 +fnull = open(os.devnull, 'w')
 +~~~
 +
 +-----------------
 +
 +## Message d'erreur 
 +
 +How to print to stderr in Python?
 +
 +http://stackoverflow.com/questions/5574702/how-to-print-to-stderr-in-python
 +
 +~~~python
 +def warning(*objs):
 +    print(*objs, file=sys.stderr)
 +~~~
 +
 +## Conversion hexa
 +
 +~~~python 
 +import numpy as np
 +
 +carac=re.sub('^','0x',carac)
 +carac= int(carac, 16)
 +print(carac)
 +file.write(np.byte(carac))
 +
 +
 +with open('plop.bin', 'bw') as file:
 +        file.write(b'\x50\x40\x73')
 +        
 +        
 +hex(11) # '0xb'
 +
 +a = int('0x100', 16)
 +print(a)   #256
 +print('%x' % a) #100
 +
 +import binascii
 +binascii.unhexlify('7061756c' # b'paul'
 +
 +"{0:8b}".format(int("a",16))    # '    1010'
 +
 +~~~
 +
 +http://stackoverflow.com/questions/16843108/how-to-read-a-hex-file-into-numpy-array
 +~~~python
 +with open(myfile) as f:
 +    iv = binascii.unhexlify(f.readline().strip())
 +    key = binascii.unhexlify(f.readline().strip())
 +    count = int(f.readline())
 +    a = np.fromiter((binascii.unhexlify(line.strip()) for line in f), dtype='|S16')
 +~~~
 +
 +
 +~~~python
 +hashlib.sha512('Bonjour'.encode('utf-8')).hexdigest()
 +hex(int.from_bytes('Bonjour'.encode('utf-8'), 'big'))
 +~~~
 +
 +--------
 +
 +Créer un Dictionnaire à partir de deux listes (l'une clef, l'autre valeur)
 +
 +~~~python
 +clef = ['a', 'b', 'c']
 +valeur = [1, 2, 3]
 +dictionnaire=dict(zip(clef, valeur))
 +~~~
 +
 +## Test
 +
 +Voir :
 +* nox
 +* unittest
 +
 +## Exception
 +
 +http://stackoverflow.com/questions/16138232/is-it-a-good-practice-to-use-try-except-else-in-python
 +
 +~~~python
 +try:
 +    s   
 +except NameError:
 +    pass
 +else: # If no exception occured, do :
 +    s.user.logout()
 +~~~
 +
 +
 +
 +## Temps / time
 +
 +Voir :
 +* timeit
 +
 +~~~python
 +start = time.time()
 +UnifiedJob.objects.filter(id=1096679).update(status='canceled')
 +end = time.time()
 +
 +print(end - start)
 +~~~
 +
 +## Strings
 +
 +https://zerokspot.com/weblog/2015/12/31/new-string-formatting-in-python/
 +
 +## Debug
 +
 +Source : https://www.geekarea.fr/wordpress/?p=763
 +
 +Level 1
 +~~~python
 +f = open('/tmp/debug','a')
 +f.write(variable + '\n')
 +f.close()
 +~~~
 +
 +Level 2
 +~~~python
 +from pprint import pprint
 +pprint(variable.__class__.__name__, f)
 +pprint(dir(variable), f)
 +pprint(vars(variable), f)
 +~~~
 +
 +Level 3 (sur une exception)
 +~~~python
 +import traceback
 +f.write(str(traceback.format_exc()))
 +~~~
 +
 +
 +## map reduce filter
 +
 +Voir : 
 +* [[notes_python_multithreading|Alternatives Multi threads à map]]
 +
 +
 +## Aures
 +
 +A noter que sur RedHat 8 le chemin vers python est ''/usr/libexec/platform-python''
  

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki