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 ?
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
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
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With