0

I've written something to convert html table to csv and it has a part like this:

out_csv = csv.writer(sys.stdout)

for row in table:
   out_csv.writerow(row.to_csv())


It works just fine until I pipe into a program that doesn't use the full output, i.e:
python file.py | head -5. Now the file closes after the 5th line and I get a BrokenPipeError.

I know I could put the whole code into a try and except block, but from what I gather its bad practice and it isn't very readable either.

Is there any other way I could deal with this?

iaquobe
  • 555
  • 1
  • 6
  • 23
  • Why would handling an exception be bad practice? – Klaus D. Apr 13 '20 at 10:33
  • Answered here: [Catch Broken Pipe in Python 2 AND Python 3](https://stackoverflow.com/questions/34718208/catch-broken-pipe-in-python-2-and-python-3) — Except you don’t need to care about Python 2 any more. – Konrad Rudolph Apr 13 '20 at 10:37
  • Not in general but putting the whole code in one. That is what I've been told by my teachers. – iaquobe Apr 13 '20 at 10:37
  • 1
    @jaklh You don’t need to put your *whole code* into the try block, only the part that might need to deal with broken pipes. – Konrad Rudolph Apr 13 '20 at 10:38

0 Answers0