如何给sys.stdin赋值?
How to assign a specific value to 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?
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?
这似乎有效:
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?
我正在使用以下代码:
#!/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?
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?
这似乎有效:
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?