Write function result to stdin

20,103

Solution 1

You could mock stdin with a file-like object?

import sys
import StringIO

oldstdin = sys.stdin
sys.stdin = StringIO.StringIO('asdlkj')

print raw_input('.')       #  .asdlkj

Solution 2

I was googling how to do this myself and figured it out. For my situation I was taking some sample input from hackerrank.com and putting it in a file, then wanted to be able to use said file as my stdin, so that I could write a solution that could be easily copy/pasted into their IDE. I made my 2 python files executable, added the shebang. The first one reads my file and writes to stdout.

#!/Users/ryandines/.local/share/virtualenvs/PythonPractice-U9gvG0nO/bin/python
# my_input.py
import sys

def read_input():
    lines = [line.rstrip('\n') for line in open('/Users/ryandines/Projects/PythonPractice/swfdump')]
    for my_line in lines:
        sys.stdout.write(my_line)
        sys.stdout.write("\n")

read_input()

The second file is the code I'm writing to solve a programming challenge. This was mine:

#!/Users/ryandines/.local/share/virtualenvs/PythonPractice-U9gvG0nO/bin/python
def zip_stuff():

    n, x = map(int, input().split(' '))
    sheet = []

    for _ in range(x):
        sheet.append( map(float, input().split(' ')) )

    for i in zip(*sheet): 
        print( sum(i)/len(i) )

zip_stuff()

Then I use the operating system's pipe command to provide the buffering of STDIN. Works exactly like hackerrank.com, so I can easily cut/paste the sample input and also my corresponding code without changing anything. Call it like this: ./my_input.py | ./zip_stuff.py

Solution 3

It is possible on Linux:

import fcntl, termios
import os
tty_path = '/proc/{}/fd/0'.format(os.getpid())

with open(tty_path, 'w') as tty_fd:
        for b in 'Testy !\n':
            fcntl.ioctl(tty_fd, termios.TIOCSTI,b)
# input()

Share:
20,103
m_vdbeek
Author by

m_vdbeek

Currently working as a web developer at Sagacify.

Updated on December 09, 2021

Comments

  • m_vdbeek
    m_vdbeek over 2 years

    I'm trying to write the results of a function to stdin.

    This is the code :

    def testy():
        return 'Testy !'
    
    import sys
    sys.stdin.write(testy())
    

    And the error I get is :

    Traceback (most recent call last):
      File "stdin_test2.py", line 7, in <module>
        sys.stdin.write(testy())
    io.UnsupportedOperation: not writable
    

    I'm not completely sure, is this the right way of doing things ?

  • m_vdbeek
    m_vdbeek about 11 years
    I think I'm going to try this solution. Thanks !
  • The Matt
    The Matt over 5 years
    While it does not solve this question, turns out you can write to stdin
  • orbeckst
    orbeckst over 4 years
    For Python 3: from io import StringIO and sys.stdin = StringIO('asdlkj').
  • Ahndwoo
    Ahndwoo over 4 years
    Hey thanks, this is exactly the same use case as I have :) Works like a charm!
  • tharibo
    tharibo about 3 years
    Hey Ryan, nicely done. Do you know you can directly use a file as input with the command line, so that you don't need to write your first program at all? Or am I missing something?: ./zip_stuff.py < '/Users/ryandines/Projects/PythonPractice/swfdump'
  • Ryan Dines
    Ryan Dines about 3 years
    @tharibo yep, you're right, or just cat the file cat swfdump | ./zip_stuff.py, although for hackerrank I needed some specific behavior...i dont really remember TBH