Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
python read function
#1
Can I read from the stdin in binary? the function input() and os.stdin.read() both require "utf-8". I want to do this because my python homework testing framework use "./xxx.py < input.txt" to run my python script, but the input.txt may contain some random binary value. How can I handle this ?
Reply
#2
Use the underlying buffer member of the stdin stream
binary = sys.stdin.buffer.read(1024)
Reply
#3
From the docs under sys.stdin
Quote:Note To write or read binary data from/to the standard streams, use the underlying binary buffer object. For example, to write bytes to stdout, use sys.stdout.buffer.write(b'abc')....

So something like:
import sys

binary_data = sys.stdin.buffer.read()
print(binary_data)
Output:
$ echo -e '\x15\x12' | python3 read_stdin.py b'\x15\x12\n'
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to call/read function for all elements in my list in python johnny_sav1992 1 2,068 Jul-27-2020, 04:19 PM
Last Post: buran
  How should i read H_T function in below program? Shahnaz 1 1,768 Jan-29-2019, 05:41 PM
Last Post: Larz60+
  Setting Byte Count in pyVisa Read Function mike505 0 5,054 Nov-17-2016, 07:43 PM
Last Post: mike505

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020