Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write function result to stdin

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 ?

like image 784
m_vdbeek Avatar asked Feb 24 '13 19:02

m_vdbeek


3 Answers

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
like image 132
Pavel Anossov Avatar answered Oct 19 '22 19:10

Pavel Anossov


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

like image 2
Ryan Dines Avatar answered Oct 19 '22 19:10

Ryan Dines


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()

like image 1
Adam Jenča Avatar answered Oct 19 '22 19:10

Adam Jenča