else/Safeprint/safeprint.py

19 lines
613 B
Python
Raw Normal View History

2016-12-23 03:42:21 +00:00
'''
This function is slow and ugly, but I need a way to safely print unicode strings
on systems that don't support it without crippling those who do.
'''
2017-11-03 19:50:16 +00:00
def safeprint(text, file_handle=None, end='\n'):
2016-12-23 03:42:21 +00:00
for character in text:
try:
if file_handle:
file_handle.write(character)
else:
print(character, end='', flush=False)
except UnicodeError:
if file_handle:
file_handle.write('?')
else:
print('?', end='', flush=False)
if not file_handle:
2017-11-03 19:50:16 +00:00
print(end, end='', flush=True)