2

I want python code read from stdin and write to stdout.

Here is a code I am trying

#!/usr/bin/python
# filename: pass.py
import sys
import numpy as N
a = N.frombuffer(sys.stdin.buffer.read(), dtype = 'b', count = -1)
a.tofile(sys.stdout.buffer)

somehow this code works:

$ seq 10 | python3 pass.py > out

but this doesn't work:

$ seq 10 | python3 pass.py 
Traceback (most recent call last):
  File "pass.py", line 6, in <module>
    a.tofile(sys.stdout.buffer)
OSError: obtaining file position failed

How can I make this code work?

auditory
  • 165
  • 6
  • Your code works on my side. Both commands, flushing into `out` or terminal. – Learning is a mess May 23 '19 at 08:57
  • @Learningisamess how about `seq 10 | python3 pass.py | python3 pass.py > out`. Does this also work? The same error on my side with python 3.7.3 – auditory May 23 '19 at 14:25
  • Not working, I get the same error as yours. I think it is an encoding issue with `stdout`, the default encoding is 'utf-8' and then you are reading bytes `N.frombuffer`. Check https://stackoverflow.com/questions/492483/setting-the-correct-encoding-when-piping-stdout-in-python/4027726 – Learning is a mess May 23 '19 at 15:14

0 Answers0