简体   繁体   中英

Python3: Using input() with stdin, like in hackerrank

I have an input file ("abc.in") which I will like to read each line as input() , exactly like how it works on hackerrank and other online coding platforms.

I have seen solutions replicating the same functionality by piping , fileinput and sys etc. On hackerrank I can just use input() to store one line of the input file as a variable. How do I do that locally? Do I store the files in the same place, what command do I use to run this in the terminal?

I thought this would be easy, but somehow I can't seem to figure out how to do it after trying for some time. Apologies if the answer was obvious.

Any help provided is greatly appreciated!

You can redirect the stdin with < on command line. Let's say you have following input stored to file data.in :

line1
line2

And you have following code stored to test.py :

print(1, input())
print(2, input())

Then you can run the script with redirected stdin:

~$ python3 test.py < data.in
1 line1
2 line2

If you want to save the output to a file you can redirect stdout as well:

~$ python3 test.py < data.in > data.out

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