首页 > 解决方案 > 如何为 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?

标签: pythonstdinpython-2.x

解决方案


这似乎有效:

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?

推荐阅读