Provo a scrivere del codice per catturare un errore di tubo rotto. Il codice dovrebbe essere eseguito in Python 2.xe Python 3.x.Catch Broken Pipe in Python 2 AND Python 3
In Python 2.xa tubo rotto è rappresentato da un socket.error
socket.error: [Errno 32] Broken pipe
Ciò è stato cambiato in Python 3.x - un tubo rotto ora è un BrokenPipeError
BrokenPipeError: [Errno 32] Broken pipe
Anche la sintassi la gestione delle eccezioni è leggermente cambiata (vedi https://stackoverflow.com/a/34463112/263589), quindi quello che devo fare è qualcosa di simile:
try:
do_something()
except BrokenPipeError as e: # implies Python 3.x
resolve_for_python2()
except socket.error as e:
if sys.version_info[0] == 2: # this is necessary, as in Python >=3.3
# socket.error is an alias of OSError
# https://docs.python.org/3/library/socket.html#socket.error
resolve_for_python3()
else:
raise
C'è (almeno) un problema rimanente: In Python 2.x non c'è BrokenPipeError
, quindi ogni volta che c'è un'eccezione in do_something()
Python 2.x lancia un'altra eccezione e si lamenta che non sa BrokenPipeError
. Poiché socket.error
è deprecato in Python 3.x, un problema simile potrebbe sorgere in Python 3.x nel prossimo futuro.
Cosa posso fare per far funzionare questo codice in Python 2.xe Python 3.x?
Dai un'occhiata a http://python-future.org/compatible_idioms.html, mostrano la gestione delle eccezioni. – MKesper
http://newbebweb.blogspot.in/2012/02/python-head-ioerror-errno-32-broken.html qui è –
Grazie! Ma http://python-future.org/compatible_idioms.html#catching-exceptions non spiega come rilevare un'eccezione che non esiste in Python 2 o Python 3 ma è obbligatoria nell'altra versione. – speendo