如何将特定值分配给sys.stdin?

3

我正在使用以下代码:

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

1
将字符串分配给 sys.stdin 是非常疯狂的。这样做会破坏 Python,因为它期望该名称引用一个类似文件的对象,可以在其上调用诸如.read().readline()之类的方法。如果您想逐行处理字符串,请使用 for line in myString.splitlines():,例如-无需在此过程中搞乱sys模块。 - jasonharper
2个回答

2
这似乎有效:最初的回答。
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?

假设data的内容是一个环境变量。我该如何将其内容存储在data中?我最接近的方法是print(os.environ['EvanT']),但当我将其放入data中时,它只会打印实际文本print(os.environ['EvanT']),而不是EvanT变量的内容。 - user2831586
1
类似 StringIO(os.environ['EvanT'] + '\n') 的东西应该可以工作。 - martineau
我遇到了以下错误:TypeError: initial_value must be unicode or None, not str。我该如何修复? - user2831586
1
StringIO(os.environ['EvanT'] + u'\n') - martineau

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?

你为什么导入StringIO? - Kirk Strauser
@KirkStrauser 抱歉,这是从问题中复制粘贴的问题。 - Inder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接