fix hidconsole for python 2/3

This commit is contained in:
Daniel Pavel 2013-05-06 17:38:09 +02:00
parent 6b75286885
commit 79cd52833c
1 changed files with 11 additions and 14 deletions

View File

@ -29,7 +29,7 @@ strhex = lambda d: hexlify(d).decode('ascii').upper()
try: try:
unicode unicode
# this is certanly Python 2 # this is certanly Python 2
is_string = lambda d: isinstance(d, unicode) or isinstance(d, str) is_string = lambda d: isinstance(d, unicode)
# no easy way to distinguish between b'' and '' :( # no easy way to distinguish between b'' and '' :(
# or (isinstance(d, str) \ # or (isinstance(d, str) \
# and not any((chr(k) in d for k in range(0x00, 0x1F))) \ # and not any((chr(k) in d for k in range(0x00, 0x1F))) \
@ -74,6 +74,11 @@ def _print(marker, data, scroll=False):
else: else:
sys.stdout.write('\n') sys.stdout.write('\n')
# flush stdout manually...
# because trying to open stdin/out unbuffered programatically
# works much too differently in Python 2/3
sys.stdout.flush()
def _error(text, scroll=False): def _error(text, scroll=False):
_print("!!", text, scroll) _print("!!", text, scroll)
@ -183,13 +188,6 @@ def main():
# file may not exist yet # file may not exist yet
pass pass
# re-open stdout unbuffered
try:
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
except:
# will fail in python3
pass
try: try:
from threading import Thread from threading import Thread
t = Thread(target=_continuous_read, args=(handle,)) t = Thread(target=_continuous_read, args=(handle,))
@ -227,13 +225,12 @@ def main():
print ("") print ("")
else: else:
time.sleep(1) time.sleep(1)
except Exception as e:
print ('%s: %s' % (type(e).__name__, e))
print (".. Closing handle %r" % handle) finally:
hidapi.close(handle) print (".. Closing handle %r" % handle)
if interactive: hidapi.close(handle)
readline.write_history_file(args.history) if interactive:
readline.write_history_file(args.history)
if __name__ == '__main__': if __name__ == '__main__':