From 3137d3a3153b4ffb68b32c6283759a72f1ecbb2f Mon Sep 17 00:00:00 2001 From: Vincent Le Gallic Date: Fri, 16 May 2014 01:37:46 +0200 Subject: [PATCH] prompt() ne crashe pas salement mais propose de retenter son coup MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Parce que recommencer tout son câblage parce qu'on a foiré la redirection mail, c'est ultra-chiant. --- gestion/affich_tools.py | 44 +++++++++++++++++++++++++++++------------ 1 file changed, 31 insertions(+), 13 deletions(-) diff --git a/gestion/affich_tools.py b/gestion/affich_tools.py index f29aaa13..31fa565d 100755 --- a/gestion/affich_tools.py +++ b/gestion/affich_tools.py @@ -7,7 +7,14 @@ Copyright (C) Frédéric Pauget Licence : GPLv2 """ -import sys, re, os, tempfile, subprocess +import sys +import re +import os +import tempfile +import subprocess +if not "/usr/scripts" in sys.path: + sys.path.append("/usr/scripts") +import cranslib.cransstrings # Détermination de l'encodage encoding = None @@ -290,21 +297,32 @@ def get_screen_size(): except: return (24, 80) -def prompt(prompt, defaut='', couleur='gras'): - u""" +def prompt(prompt, defaut=u'', couleur='gras'): + """ Pose la question prompt en couleur (défaut gras), retourne la réponse. """ - sys.stdout.write(coul(prompt, couleur).encode(encoding)) + prompt = cranslib.cransstrings.decode_dammit(prompt) + defaut = cranslib.cransstrings.decode_dammit(defaut) + # coul renvoie alors un unicode + prompt_s = coul(prompt, couleur) if defaut : - sys.stdout.write((" [%s]" % defaut).encode(encoding)) - sys.stdout.write(" ".encode(encoding)) - v = sys.stdin.readline() - try: - v = v.decode(encoding).strip() - except UnicodeDecodeError as error: - raise UnicodeDecodeError("%s: %r" % (error, v)) - if not v: v = defaut - return v + prompt_s += u" [%s]" % defaut + # On fait tout pour ne pas faire crasher le script appelant + # si on lève une erreur, on la rattrappe et on laisse une chance + # de refaire une proposition. + # On laisse néanmoins la possibilité de sortir sur un Ctrl+C + while True: + try: + v = raw_input(prompt_s.encode(encoding)) + v = cranslib.cransstrings.decode_dammit(v) + if not v: + v = defaut + return v + except UnicodeDecodeError as error: + try: + print "UnicodeDecodeError rattrappée (chaîne : %s)" % v + except UnicodeDecodeError as error2: + print "UnicodeDecodeError catched but could not be displayed. Trying ASCII." class anim : """ Permet de créer une animation :