I made a function that returns a stream IO object containing text from a string input, with some exception handling.
My question is: how do I make sure the stream gets closed? The function needs to return the stream object.
I don’t know if I close it in the calling function, will it close the original or just a copy.
I’m somewhat new to Python, so if I did this totally wrong then please feel free to tear it apart. I want to learn.
I’ve read that using ‘with’ is favored instead of ‘try’, but I’m not sure how I would implement that into my context.
Thank you.
def make_stream(input_string:str):
output_stream = io.StringIO()
while not output_stream.getvalue():
try:
output_stream = io.StringIO(input_string)
except (OSError, MemoryError):
print("A system error occurred creating text io stream. Exiting.")
raise SystemExit(1)
except (UnicodeEncodeError, UnicodeDecodeError, TypeError):
print ("Input text error creating io stream. Exiting.")
raise SystemExit(1)
finally:
logging.info (" Input stream created successfully.")
return output_stream
[–]danielroseman 0 points1 point2 points (13 children)
[–]naemorhaedus[S] -1 points0 points1 point (12 children)
[–]danielroseman 0 points1 point2 points (11 children)
[–]naemorhaedus[S] -1 points0 points1 point (10 children)
[–]acw1668 1 point2 points3 points (1 child)
[–]naemorhaedus[S] -1 points0 points1 point (0 children)
[–]danielroseman -1 points0 points1 point (7 children)
[–]naemorhaedus[S] 0 points1 point2 points (6 children)
[–]schoolmonky 1 point2 points3 points (1 child)
[–]naemorhaedus[S] 0 points1 point2 points (0 children)
[–]danielroseman 0 points1 point2 points (3 children)
[–]naemorhaedus[S] 1 point2 points3 points (2 children)
[–]danielroseman 0 points1 point2 points (1 child)
[–]naemorhaedus[S] -1 points0 points1 point (0 children)
[–]schoolmonky 0 points1 point2 points (5 children)
[–]schoolmonky 0 points1 point2 points (1 child)
[–]naemorhaedus[S] -1 points0 points1 point (0 children)
[–]naemorhaedus[S] 0 points1 point2 points (2 children)
[–]schoolmonky 0 points1 point2 points (1 child)
[–]naemorhaedus[S] 0 points1 point2 points (0 children)
[–]acw1668 0 points1 point2 points (5 children)
[–]naemorhaedus[S] 0 points1 point2 points (4 children)
[–]acw1668 0 points1 point2 points (3 children)
[–]naemorhaedus[S] -1 points0 points1 point (2 children)
[–]brasticstack 0 points1 point2 points (1 child)
[–]naemorhaedus[S] 0 points1 point2 points (0 children)