如何为sys.stdin分配特定值?

前端之家收集整理的这篇文章主要介绍了如何为sys.stdin分配特定值? 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在使用以下代码

#!/usr/bin/env python

import sys
from io import StringIO

#data = sys.stdin.readlines()
sys.stdin = """
hello I feel good
how are you?
where have you been?
"""
for line in sys.stdin:
    print line

当我运行上述代码时,打印行将打印出分配给sys.stdin的文本的每个字符.每行打印一个字符:

h
e
l
l
o

I

....truncated

我正在尝试将输出保存在sys.stdin中,它应如下所示:

hello I feel good
how are you?
where have you been?
最佳答案
这似乎可行:

from io import StringIO
import sys

data = u"""\
hello I feel good
how are you?
where have you been?
"""

sys.stdin = StringIO(data)

for line in sys.stdin:
    print line.rstrip()

输出

hello I feel good
how are you?
where have you been?
原文链接:https://www.f2er.com/python/533180.html

猜你在找的Python相关文章