# Snippets python ### Obtenir un item aléatoire d'une liste ``` import random random.choice['a','b','c'] ``` ### Hash md5 d'un fichier ``` def get_hash(name): readsize = 64 * 1024 with open(name, 'rb') as f: data = f.read(readsize) f.seek(-readsize, os.SEEK_END) data += f.read(readsize) return hashlib.md5(data).hexdigest() ``` ### Texte aléatoire ``` def randomtext(n): # stackoverflow.com/questions/2257441 # /random-string-generation-with-upper-case-letters-and-digits-in-python/23728630#23728630 txt = ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(n)) return txt ``` ### which ``` def which(program): #https://stackoverflow.com/questions/377017/test-if-executable-exists-in-python/377028#377028 def is_exe(fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) fpath, fname = os.path.split(program) if fpath: if is_exe(program): return program else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, program) if is_exe(exe_file): return exe_file return None ``` ### Capturer CTRL-C ``` x = 1 while True: try: print x time.sleep(.3) x += 1 except KeyboardInterrupt: print "Bye" sys.exit(0) ``` ### Vérifier que l'on est connecté à internet ``` def check_connectivity(): """ check if internet access #https://stackoverflow.com/questions/3764291/checking-network-connection """ try: request.urlopen("http://www.openbsd.org", timeout=10) return True except Exception as e: print(e) return False ``` ### Equivalent à tail -f ``` def tail(filename): if not os.path.isfile(filename) : return # Watch the file for changes stat = os.stat(filename) size = stat.st_size mtime = stat.st_mtime while True: time.sleep(0.5) stat = os.stat(filename) if mtime < stat.st_mtime: mtime = stat.st_mtime with open(filename, "rb") as f: f.seek(size) lines = f.readlines() ul = [ u.decode() for u in lines ] yield("".join(ul).strip()) size = stat.st_size ```