2

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?
  2. Is print is like stdout?

I ask it cause I saw this order in facebook demo puzzle:

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"

2 Answers 2

6

When you are reading from stdin, you have three basic options:

  • 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.


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. 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.
Sign up to request clarification or add additional context in comments.

1 Comment

You missed sys.stdin = fileobject
2

If you want to run code so that a file is read from stdin (instead of from an interactive terminal), then use redirection.

python program.py <input_file.txt

The < means the named file will be attached to stdin when the script is run. This syntax is the same on Windows, MacOS, and Unix-like platforms.

2 Comments

Thanks, I added a part about the stdout. can you answer this as well?
@ZoZo123 stdout is just > out_file.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.