简体   繁体   中英

How to pass multiple lines as an input to stdin (Python)

Suppose the sample input is this:

"1 2 3"
"hello"
"hi there"
"x y z"
"5 6 7"

This should be passed into stdin and the output should simply print them to stdout

I have the following code in sample.py , and I'm using Eclipse as my IDE.

import fileinput

for line in fileinput.input():
    print line

If I'm using a command line, I might be able to do something like

python sample.py "1 2 3 \n hello"

to pass the input to stdin. But how should I do this on Eclipse(when there are multiple lines that should be inputted into stdin)?


Since I didn't know how to do this, I simply put the lines into a txt file and read from it.

On Windows,

  1. Add Python directory to the environment variable PATH (ex. C:\\Python27)
  2. put all the lines into some text file (ex. input.txt should contain "hello \\n hello")
  3. run cmd
  4. go to the directory where the source code and input file are
  5. run python sample.py < input.txt

Then you get an output in stdout !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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