将函数结果写入标准输入

15 投票
4 回答
27661 浏览
提问于 2025-04-17 16:57

我正在尝试把一个函数的结果写入标准输入。

这是我的代码:

def testy():
    return 'Testy !'

import sys
sys.stdin.write(testy())

我遇到的错误是:

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

我不太确定,这样做是不是正确的方式?

4 个回答

1

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

2

我在网上查找如何自己做这件事,最后搞明白了。对于我的情况,我从hackerrank.com上拿了一些示例输入,放到一个文件里,然后想把这个文件当作我的 stdin(标准输入),这样我就可以写一个解决方案,方便直接复制粘贴到他们的在线编程环境中。我把我的两个Python文件设置成可执行的,并添加了shebang(文件头)。第一个文件读取我的文件内容,然后把结果写到 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()

第二个文件是我用来解决编程挑战的代码。这是我的代码:

#!/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()

接着我使用操作系统的管道命令来处理标准输入的缓冲。这和hackerrank.com的工作方式完全一样,所以我可以轻松地复制粘贴示例输入和我对应的代码,而不需要做任何修改。调用方式是这样的: ./my_input.py | ./zip_stuff.py

28

你可以用一个像文件一样的对象来模拟 stdin 吗?

import sys
import StringIO

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

print raw_input('.')       #  .asdlkj

撰写回答