Write function result to stdin

一曲冷凌霜 提交于 2019-12-19 03:01:09

问题


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 ?


回答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



回答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




回答3:


stdin is an input stream, not an output stream. You can't write to it.

What you might be able to do, possibly, is create a pipe using os.pipe, turn the readable end into a file object using os.fdopen, and replace stdin with that, and then write to the writeable end.

r, w = os.pipe()
new_stdin = os.fdopen(r, 'r')
old_stdin, sys.stdin = sys.stdin, new_stdin

I can't see that ending well, though. It will be easier and less error-prone to just rewrite the parts of your application that are using input.



来源:https://stackoverflow.com/questions/15055524/write-function-result-to-stdin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!