简体   繁体   English

如何阅读和检查python中的stdin / stdout?

[英]How to read and check stdin/stdout in python?

We have this good answer for how to read stdin. 对于如何读取标准输入,我们有这个很好的答案。

  1. But I don't understand how do I run the python code so it will read from a file as stdin ? 但我不明白如何运行python代码,以便它将从文件中读取为stdin
  2. Is print is like stdout ? print是否像stdout

I ask it cause I saw this order in facebook demo puzzle: 我问它因为我在facebook演示拼图中看到了这个订单:

NOTE: You need to write the full code taking all inputs are from stdin and outputs to stdout If you are using "Java", the classname is "Solution" 注意:您需要编写完整代码,所有输入都来自stdin和输出到stdout如果您使用的是“Java”,则类名为“Solution”

When you are reading from stdin , you have three basic options: 当您从stdin阅读时,您有三个基本选项:

  • type stuff manually: 手动输入东西:

     $ python hello.py asfasfasf asfasfasfasfasf <TYPE CONTROL-D TO END STREAM> 
  • Using < : 使用<

     $ python hello.py < inputfile.txt 
  • Using the output from a previous command: 使用上一个命令的输出:

     $ cat inputfile.txt | grep oranges | python hello.py 

All three of these will give you input via stdin . 所有这三个都会通过stdin给你输入。


After editing your question, you are no longer asking the same question. 编辑完问题后,您不再提出同样的问题。 Here is the answer to your new questions: 以下是您的新问题的答案:

  1. You can do sys.stdin = open('inputfile.txt') to have the input file look like stdin. 您可以执行sys.stdin = open('inputfile.txt')以使输入文件看起来像stdin。 Make sure this is what you want. 确保这是你想要的。 From your homework prompt, it sounds like my above solution is what you want. 从你的作业提示,听起来我的上述解决方案是你想要的。
  2. print writes to stdout. print写入stdout。

If you want to run code so that a file is read from stdin (instead of from an interactive terminal), then use redirection. 如果要运行代码以便从stdin(而不是从交互式终端)读取文件 ,则使用重定向。

python program.py <input_file.txt

The < means the named file will be attached to stdin when the script is run. <表示在运行脚本时,指定文件将附加到stdin。 This syntax is the same on Windows, MacOS, and Unix-like platforms. 这种语法在Windows,MacOS和类Unix平台上是相同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM