[英]Write function result to stdin
我正在尝试将函数的结果写入标准输入。
这是代码:
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
我不完全确定,这是正确的做事方式吗?
你可以用类似文件的对象来模拟stdin
吗?
import sys
import StringIO
oldstdin = sys.stdin
sys.stdin = StringIO.StringIO('asdlkj')
print raw_input('.') # .asdlkj
stdin
是输入流,而不是输出流。 你不能写信给它。
你可能做的可能是使用os.pipe
创建一个管道,使用os.fdopen
将可读端转换为文件对象,并用它替换stdin,然后写入可写端。
r, w = os.pipe()
new_stdin = os.fdopen(r, 'r')
old_stdin, sys.stdin = sys.stdin, new_stdin
不过,我看不出那个结局。 只重写使用input
应用程序部分会更容易,也更不容易出错。
我正在谷歌上搜索自己如何做到这一点,并想出来。 对于我的情况,我从hackerrank.com获取一些示例输入并将其放入文件中,然后希望能够将所述文件用作我的stdin
,以便我可以编写一个可以轻松复制/粘贴到其IDE中的解决方案。 我让我的2个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()
然后我使用操作系统的管道命令来提供STDIN的缓冲。 与hackerrank.com完全一样,所以我可以轻松地剪切/粘贴样本输入以及相应的代码,而无需更改任何内容。 这样称呼: ./my_input.py | ./zip_stuff.py
./my_input.py | ./zip_stuff.py
在 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.