python - 如何为 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?
推荐阅读
- ruby - 什么是`&&=`快捷方式?
- java - 如何制作一个与外部硬件通信的 asnychron REST 服务器
- c# - 尝试在 SQL Server 中更新 datagridview 上的值
- sql - 在 SQL Server 中,BCP shell 命令不是在一个服务器中写入文件,而是在另一个服务器中创建文件。这个问题需要任何许可吗?
- javascript - 浏览器调整大小再次运行功能,我该怎么做?
- python - 这段代码可以更简单吗?哪个代码看起来更好?[反向循环]
- r - 始终使用列表中的一行 n 个其他数据框创建所有可能的数据框
- python - 熊猫 to_datetime 方法
- django - 如何在 Django 中通过 HttpResponse 或 JsonResponse 发送多个对象
- angular - 响应头年龄控制