使用 python 从重定向的标准输入读取文件 [英] Read a File from redirected stdin with python
问题描述
我正在尝试读取通过命令行重定向 stdin 的文本文件的内容,并在接收者必须将其组装回原始形式时通过 Internet 发送它.
I am trying to read the content of a text file that was redirected stdin via the command line, and send it by the Internet when the receiver has to assemble it back to it's original form.
例如:
$ python test.py < file.txt
我尝试读取文件并使用以下代码将其组装回 链接:
I have tried to read the file and to assemble it back with the following code inspired by link:
for line in sys.stdin:
stripped = line.strip()
if not stripped: break
result = result + stripped
print "File is beeing copied"
file = open("testResult.txt", "w")
file.write(result)
file.close()
print "File copying is complete!"
但是只要我的文件中没有空行(两个 '\n' 一个接一个),这个解决方案就可以工作,如果我有,我的循环会中断并且文件读取结束.我怎么读从标准输入直到我到达被重定向的文件的 <>?
But this solution works as long as I DON'T have an empty row( two '\n' one after another) in my file,if i do have, my loop breaks and the File reading ends.How can I read from stdin till i reach <> of the file that was redirected?
推荐答案
你为什么还要看数据:
result = sys.stdin.read()
这篇关于使用 python 从重定向的标准输入读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!