From f81af33fcda34f1f0c12c01dcc8481f04377d1d3 Mon Sep 17 00:00:00 2001 From: max ulidtko Date: Wed, 17 Feb 2021 14:37:22 +0200 Subject: Fix #109: reading binary data from sys.stdin --- tftpy/TftpContexts.py | 3 ++- tftpy/compat.py | 15 +++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) create mode 100644 tftpy/compat.py diff --git a/tftpy/TftpContexts.py b/tftpy/TftpContexts.py index da85886..418aac4 100644 --- a/tftpy/TftpContexts.py +++ b/tftpy/TftpContexts.py @@ -15,6 +15,7 @@ from .TftpShared import * from .TftpPacketTypes import * from .TftpPacketFactory import TftpPacketFactory from .TftpStates import * +from . import compat import socket import time import sys @@ -281,7 +282,7 @@ class TftpContextClientUpload(TftpContext): if hasattr(input, 'read'): self.fileobj = input elif input == '-': - self.fileobj = sys.stdin + self.fileobj = compat.binary_stdin() else: self.fileobj = open(input, "rb") diff --git a/tftpy/compat.py b/tftpy/compat.py new file mode 100644 index 0000000..0049396 --- /dev/null +++ b/tftpy/compat.py @@ -0,0 +1,15 @@ +import sys + +def binary_stdin(): + """ + Get a file object for reading binary bytes from stdin instead of text. + Compatible with Py2/3, POSIX & win32. + Credits: https://stackoverflow.com/a/38939320/531179 (CC BY-SA 3.0) + """ + if hasattr(sys.stdin, 'buffer'): # Py3+ + return sys.stdin.buffer + else: + if sys.platform == 'win32': + import os, msvcrt + msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY) + return sys.stdin -- cgit v1.2.1