Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you read from stdin?

Tags:

python

stdin

I'm trying to do some of the code golf challenges, but they all require the input to be taken from stdin. How do I get that in Python?

like image 732
tehryan Avatar asked Sep 20 '09 05:09

tehryan


People also ask

What does it mean to read from stdin?

Short for standard input, stdin is an input stream where data is sent to and read by a program. It is a file descriptor in Unix-like operating systems, and programming languages, such as C, Perl, and Java. Below, is an example of how STDIN could be used in Perl.


2 Answers

You could use the fileinput module:

import fileinput  for line in fileinput.input():     pass 

fileinput will loop through all the lines in the input specified as file names given in command-line arguments, or the standard input if no arguments are provided.

Note: line will contain a trailing newline; to remove it use line.rstrip()

like image 83
8 revs, 8 users 48% Avatar answered Sep 19 '22 15:09

8 revs, 8 users 48%


There's a few ways to do it.

  • sys.stdin is a file-like object on which you can call functions read or readlines if you want to read everything or you want to read everything and split it by newline automatically. (You need to import sys for this to work.)

  • If you want to prompt the user for input, you can use raw_input in Python 2.X, and just input in Python 3.

  • If you actually just want to read command-line options, you can access them via the sys.argv list.

You will probably find this Wikibook article on I/O in Python to be a useful reference as well.

like image 39
Mark Rushakoff Avatar answered Sep 19 '22 15:09

Mark Rushakoff