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

时间:2019-03-02 23:33:22

标签: python stdin python-2.x

我正在使用以下代码:

#!/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?

2 个答案:

答案 0 :(得分:1)

dabba.txt文件的内容:

hello I feel good
how are you?
where have you been?

这是del.py文件中的代码

import sys
datq=sys.stdin.readlines()
for line in datq:
    print(line)

从ubuntu 18.04中的命令行:

cat dabba.txt | python del.py 

上面的代码的输出是:

hello I feel good

how are you?

where have you been?

答案 1 :(得分:1)

这似乎可行:

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?